MainThreadClass.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776
  1. using CCDCount.DLL.SqlDataClass;
  2. using CCDCount.DLL.Tools;
  3. using CCDCount.MODEL.CameraClass;
  4. using CCDCount.MODEL.ConfigModel;
  5. using CCDCount.MODEL.ResultModel;
  6. using CCDCount.MODEL.ShuLiModel;
  7. using LogClass;
  8. using MvCameraControl;
  9. using System;
  10. using System.Collections.Concurrent;
  11. using System.Collections.Generic;
  12. using System.Diagnostics;
  13. using System.Drawing;
  14. using System.IO;
  15. using System.Linq;
  16. using System.Runtime.InteropServices;
  17. using System.Runtime.Remoting.Messaging;
  18. using System.Text;
  19. using System.Threading;
  20. namespace CCDCount.DLL
  21. {
  22. public class MainThreadClass
  23. {
  24. #region 变量与实例
  25. Thread SwitchIdentifyImageThread = null;
  26. private bool IsSwitch = false;
  27. public ShuLiClass shuLiClass = null;
  28. CameraClass cameraClass = new CameraClass();
  29. public ShuLiConfigClass shuLiConfig = null;
  30. public CameraConfig cameraConfig = null;
  31. public bool CameraConfigIsChange = false;
  32. public int ThisCamerNo = -1;
  33. public bool CameraStatic { get { return _CameraStatic; } }
  34. private bool _CameraStatic = false;
  35. // 返回交换线程状态
  36. public bool CameraRunStatic { get { return IsSwitch; } }
  37. public bool IsOpenLoadThread { get { return _IsOpenLoadThread; }}
  38. private bool _IsOpenLoadThread = false;
  39. public int HistoryActiveNum { get { return shuLiClass.GetHistoryActiveNum(); } }
  40. public int OkHistoryNum { get { return shuLiClass.GetOkHistoryNum(); } }
  41. public int NgHistoryNum { get { return shuLiClass.GetNgHistoryNum(); } }
  42. // 数粒信息发送线程
  43. Thread SendBottLogicMessageThread = null;
  44. bool IsSend = false;
  45. // Modbus客户端实例
  46. public ModbusTcpClient modbusTcpClient = new ModbusTcpClient();
  47. // 颗粒结果待发送队列
  48. ConcurrentQueue<ushort> SendQueue = new ConcurrentQueue<ushort>();
  49. /// <summary>
  50. /// 数粒状态计时器
  51. /// </summary>
  52. Stopwatch stopwatch = Stopwatch.StartNew();
  53. /// <summary>
  54. /// 数粒状态
  55. /// </summary>
  56. private bool _ShuLiState = true;
  57. public bool ShuLiState { get { return _ShuLiState; } }
  58. private bool _IsDebug = true;
  59. public bool IsDebug { get { return _IsDebug; } }
  60. private bool IsConnectModbus = false;
  61. public static ActionMesSqliteDataClass actionMesSqliteDataClass = null;
  62. ConcurrentQueue<IImage> _images = new ConcurrentQueue<IImage>();
  63. public string FormulationName { get; set; } = string.Empty;
  64. public bool IsLoadFormulation = false;
  65. #endregion
  66. #region 公共方法
  67. /// <summary>
  68. /// 设置ModbusTcpClient
  69. /// </summary>
  70. /// <param name="modbusTcpClient"></param>
  71. public void ConnectModbus(string ipAddress)
  72. {
  73. if (!modbusTcpClient.Connect(ipAddress))
  74. {
  75. FaultLog.RecordErrorMessage($"MianThread{cameraConfig.CamerNo}-Modbus通讯连接失败,目标IP:{ipAddress}");
  76. return;
  77. }
  78. IsConnectModbus = true;
  79. }
  80. /// <summary>
  81. /// 初始化构造方法
  82. /// </summary>
  83. /// <param name="configClass"></param>
  84. /// <param name="CameraConfig"></param>
  85. public MainThreadClass(ShuLiConfigClass configClass,CameraConfig CameraConfig)
  86. {
  87. shuLiConfig = configClass;
  88. cameraConfig = CameraConfig;
  89. // 数粒配置文件地址
  90. if (configClass!=null)
  91. {
  92. // 创建数粒对象(配置文件)
  93. shuLiClass = new ShuLiClass(shuLiConfig);
  94. }
  95. else
  96. {
  97. // 创建数粒对象(默认)
  98. shuLiClass = new ShuLiClass();
  99. }
  100. _IsOpenLoadThread = cameraConfig.IsOpenLoad;
  101. ThisCamerNo = cameraConfig.CamerNo;
  102. actionMesSqliteDataClass = new ActionMesSqliteDataClass($"{AppDomain.CurrentDomain.BaseDirectory}DATA\\ActiveObjectData\\Cam{cameraConfig.CamerNo}\\ActiveObjectData{DateTime.Now:yyyyMMdd}.db");
  103. actionMesSqliteDataClass.GetAllActionMinStartMaxEndLine(out int num, out int StartLine, out int EndLine);
  104. shuLiClass.InitCurrentLine(EndLine);
  105. //shuLiClass.InitNum(num);
  106. }
  107. /// <summary>
  108. /// 加载相机
  109. /// </summary>
  110. /// <returns></returns>
  111. public bool LoadCamera()
  112. {
  113. bool result = false;
  114. // 相机列表
  115. try
  116. {
  117. // 获取相机列表
  118. cameraClass.GetCameraList(out List<CameraInfoClass> list);
  119. if (list.Count == 0)
  120. {
  121. FaultLog.RecordErrorMessage(string.Format("{0}:没有相机", "MainThreadClass-StartMianThread"));
  122. // 如果没有相机,则退出
  123. return result;
  124. }
  125. // 加载相机
  126. // cameraClass.LoadCamereDevice(list.First().DeviceSN);
  127. if (!cameraClass.LoadCamereDevice(cameraConfig))
  128. {
  129. FaultLog.RecordErrorMessage(string.Format("{0}:相机加载失败", "MainThreadClass-StartMianThread"));
  130. return result;
  131. }
  132. CameraConfigIsChange = false;
  133. }
  134. catch
  135. {
  136. }
  137. return result;
  138. }
  139. /// <summary>
  140. /// 重新加载相机配置
  141. /// </summary>
  142. public void ReLoadCameraConfig()
  143. {
  144. if(CameraConfigIsChange)
  145. {
  146. CameraConfig OldcameraConfig = cameraClass.GetConfigValue();
  147. if(OldcameraConfig.CameraSNNum != cameraConfig.CameraSNNum)
  148. {
  149. cameraClass.LoadCamereDevice(cameraConfig);
  150. }
  151. else
  152. {
  153. cameraClass.ReLoadCameraConfig(cameraConfig);
  154. }
  155. }
  156. }
  157. /// <summary>
  158. /// 开始主线程
  159. /// </summary>
  160. public bool StartMianThread()
  161. {
  162. bool result = false;
  163. try
  164. {
  165. // 取图线程开启
  166. if(!cameraClass.StartCamera())
  167. {
  168. return result;
  169. }
  170. _CameraStatic = true;
  171. StartSendBottLogicMessageThread();
  172. // 数据交换线程开启
  173. StartSwitchThread();
  174. // 为数粒算法的识别成功一粒回调函数添加方法
  175. shuLiClass.WorkCompleted += Worker_OneGrainCompleted;
  176. // 开启识别线程
  177. shuLiClass.StartIdentifyFuntion(cameraClass.GetCamereImageSize().Width);
  178. result = true;
  179. }
  180. catch
  181. {
  182. }
  183. return result;
  184. }
  185. /// <summary>
  186. /// 停止主线程
  187. /// </summary>
  188. public bool StopMianThread()
  189. {
  190. bool result = false;
  191. try
  192. {
  193. _CameraStatic = false;
  194. shuLiClass.WorkCompleted -= Worker_OneGrainCompleted;
  195. // 相机取图关闭
  196. cameraClass.StopCamera();
  197. // 数据交换线程关闭
  198. StopSwitchThread();
  199. // 数粒识别线程关闭
  200. shuLiClass.StopIdentifyFuntion();
  201. StopSendBottLogicMessageThread();
  202. result = true;
  203. }
  204. catch
  205. {
  206. }
  207. return result;
  208. }
  209. /// <summary>
  210. /// 释放相机资源
  211. /// </summary>
  212. public void DisposeCamera()
  213. {
  214. cameraClass.StopCamera();
  215. cameraClass.DisPoseCamera();
  216. }
  217. /// <summary>
  218. /// 重加载相机
  219. /// </summary>
  220. /// <param name="CameraSN"></param>
  221. /// <returns></returns>
  222. public bool ReLoadCamera(string CameraSN)
  223. {
  224. bool result = false;
  225. result = cameraClass.ReLoadCameraDevice(CameraSN);
  226. if (result)
  227. {
  228. cameraConfig = cameraClass.GetConfigValue();
  229. }
  230. return result;
  231. }
  232. /// <summary>
  233. /// 获取显示用的图片数据
  234. /// </summary>
  235. /// <param name="ImageHeight"></param>
  236. /// <param name="Data"></param>
  237. public void GetShowImage(int ImageHeight,out Bitmap ImageData)
  238. {
  239. List<RowStartEndCol> RowsShowList = new List<RowStartEndCol>();
  240. ActiveObjectClass NewActive = shuLiClass.GetLastActive();
  241. if (NewActive == null)
  242. {
  243. LOG.log(string.Format("{0}:没有获取到数粒数据", "MainThreadClass-GetShowImage"));
  244. ImageData = GetNullShowImage(4096, 2000);
  245. return;
  246. }
  247. List<ActiveObjectClass> Data = shuLiClass.GetHistoryActive().Where(o => o.LastSeenLine > NewActive.LastSeenLine - ImageHeight).ToList();
  248. Bitmap BitmapImage = new Bitmap(NewActive.ImageWidth, ImageHeight);
  249. if (Data.Count > 0)
  250. {
  251. int ThisImageStartLine = (int)Data.Max(o => o.LastSeenLine) - ImageHeight;
  252. using (Graphics g = Graphics.FromImage(BitmapImage))
  253. {
  254. g.Clear(Color.White);
  255. var redPen = new Pen(Color.Red, 1);
  256. var bluePen = new Pen(Color.FromArgb(0,146,255), 1);
  257. var GreenPen = new Pen(Color.SeaGreen, 5);
  258. using (Pen RedPan = new Pen(Color.Red, 5))
  259. {
  260. for (int i = 0; i < shuLiClass.ChannelsRoi.Count - 1; i++)
  261. {
  262. g.DrawLine(RedPan, new Point(shuLiClass.ChannelsRoi[i], 0), new Point(shuLiClass.ChannelsRoi[i], BitmapImage.Height));
  263. }
  264. }
  265. foreach (var item in Data)
  266. {
  267. int roix = item.MinStartCol - 5;
  268. int roiy = (int)(item.StartLine - ThisImageStartLine) - 5 < 0 ? 0 : (int)(item.StartLine - ThisImageStartLine) - 5;
  269. int roiheight = (int)(item.LastSeenLine - ThisImageStartLine - roiy) + 10;
  270. int roiwidth = item.MaxEndCol - item.MinStartCol + 10;
  271. g.DrawRectangle(GreenPen, new Rectangle(roix, roiy, roiwidth, roiheight));
  272. Font font = new Font("Arial", 40);
  273. g.DrawString(item.Num.ToString(), font, Brushes.Black, new Point(roix - 50*item.Num.ToString().Length, roiy - 20));
  274. foreach (var item1 in item.RowsData)
  275. {
  276. if((int)(item1.RowsCol - ThisImageStartLine)<0) continue;
  277. int yPos = (int)(item1.RowsCol - ThisImageStartLine);
  278. g.DrawLine(item.StateCode == 0 ? bluePen : redPen, new Point(item1.StartCol, yPos), new Point(item1.EndCol, yPos));
  279. }
  280. }
  281. }
  282. }
  283. ImageData = BitmapImage.Clone() as Bitmap;
  284. BitmapImage.Dispose();
  285. //GC.Collect();
  286. }
  287. /// <summary>
  288. /// 获取无数据的图片
  289. /// </summary>
  290. /// <param name="ImageWidth"></param>
  291. /// <param name="ImageHeight"></param>
  292. /// <param name="ImageData"></param>
  293. public Bitmap GetNullShowImage(int ImageWidth, int ImageHeight)
  294. {
  295. Bitmap BitmapImage = new Bitmap(ImageWidth, ImageHeight);
  296. using (Graphics g = Graphics.FromImage(BitmapImage))
  297. {
  298. g.Clear(Color.White);
  299. using (Pen RedPan = new Pen(Color.Red, 8))
  300. {
  301. for (int i = 0; i < shuLiClass.ChannelsRoi.Count - 1; i++)
  302. {
  303. g.DrawLine(RedPan, new Point(shuLiClass.ChannelsRoi[i], 0), new Point(shuLiClass.ChannelsRoi[i], BitmapImage.Height));
  304. }
  305. }
  306. }
  307. return BitmapImage;
  308. }
  309. /// <summary>
  310. /// 获取此刻的Config数据
  311. /// </summary>
  312. /// <param name="config"></param>
  313. public void GetAllConfigValue(out CameraConfig Camconfig,out ShuLiConfigClass shuLiConfig)
  314. {
  315. //判断是否加载了相机
  316. if(cameraClass.IsLoadCamera())
  317. {
  318. //获取已经加载的相机的配置
  319. cameraConfig = cameraClass.GetConfigValue();
  320. Camconfig = cameraConfig;
  321. }
  322. else
  323. {
  324. cameraConfig = new CameraConfig();
  325. Camconfig = cameraConfig;
  326. }
  327. //读取视觉配置
  328. shuLiConfig = shuLiClass.GetConfigValue();
  329. this.shuLiConfig = shuLiConfig;
  330. }
  331. /// <summary>
  332. /// 获取相机此刻的Config数据
  333. /// </summary>
  334. /// <param name="CameraConfig"></param>
  335. public CameraConfig GetCameraConfig()
  336. {
  337. CameraConfig result = null;
  338. //判断是否加载了相机
  339. if (cameraClass.IsLoadCamera())
  340. {
  341. //获取已经加载的相机的配置
  342. result = cameraClass.GetConfigValue();
  343. cameraConfig = result;
  344. }
  345. return result;
  346. }
  347. /// <summary>
  348. /// 保存所有Config
  349. /// </summary>
  350. public void SaveAllConfig()
  351. {
  352. shuLiClass.SaveConfig();
  353. }
  354. /// <summary>
  355. /// 获取相机连接状态
  356. /// </summary>
  357. /// <returns></returns>
  358. public bool GetCameraConnectStatic()
  359. {
  360. bool result = false;
  361. if(cameraClass != null)
  362. result = cameraClass.IsConnectCamera();
  363. return result;
  364. }
  365. /// <summary>
  366. /// 清除历史数据
  367. /// </summary>
  368. /// <returns></returns>
  369. public bool ClearHistoryActive()
  370. {
  371. bool result = false;
  372. if(shuLiClass != null)
  373. result = shuLiClass.ClearHistoryActive();
  374. return result;
  375. }
  376. /// <summary>
  377. /// 获取过去一秒内颗粒数量
  378. /// </summary>
  379. /// <returns></returns>
  380. public int GetOneSecondActiveNum()
  381. {
  382. int result = 0;
  383. if(shuLiClass != null)
  384. result = shuLiClass.GetHistoryActive().Where(o=>o.EndCheckTime>DateTime.Now-TimeSpan.FromSeconds(1)).Count();
  385. return result;
  386. }
  387. /// <summary>
  388. /// 获取相机原图一张
  389. /// </summary>
  390. /// <returns></returns>
  391. public Bitmap GetCamImageOnce()
  392. {
  393. Bitmap result = null;
  394. if(_images.Count>0)
  395. {
  396. _images.TryDequeue(out IImage image);
  397. if(image != null)
  398. result = image.ToBitmap();
  399. }
  400. return result;
  401. }
  402. /// <summary>
  403. /// 获取相机原图拼接图-50张拼一张
  404. /// </summary>
  405. /// <returns></returns>
  406. public Bitmap GetSpliceCamImageOnce()
  407. {
  408. Bitmap result = null;
  409. if (_images.Count >= 50)
  410. {
  411. CameraImageSizeClass cameraImageSize = cameraClass.GetCamereImageSize();
  412. if (cameraImageSize.Width == 0 || cameraImageSize.Height == 0)
  413. return null;
  414. result = new Bitmap(cameraImageSize.Width, cameraImageSize.Height * 50);
  415. using (Graphics g = Graphics.FromImage(result))
  416. {
  417. g.Clear(Color.White); // 设置背景色
  418. int currentY = 0;
  419. for (int i = 0; i < 50; i++)
  420. {
  421. Bitmap OutImage = GetCamImageOnce();
  422. // 将每个图像绘制到新Bitmap上
  423. g.DrawImage(OutImage, new Point(0, currentY));
  424. currentY += OutImage.Height;
  425. }
  426. }
  427. }
  428. return result;
  429. }
  430. public void ParameterTrain(List<ActiveObjectClass> ListValues)
  431. {
  432. if(ListValues.Count() > 0)
  433. {
  434. if(ListValues.Count()>500)
  435. {
  436. ListValues = ListValues.Take(500).OrderByDescending(o=>o.Area).ToList();
  437. }
  438. int MaxArea = ListValues.Max(x => x.Area);
  439. int MinArea = ListValues.Min(x => x.Area);
  440. double MaxLength = ListValues.Max(x => x.MaxLength);
  441. double MinLength = ListValues.Min(x => x.MaxLength);
  442. if(ListValues.Count<2) return;
  443. int ChazhiId = -1;
  444. int MaxChazhi = 0;
  445. for (int i = 1; i < ListValues.Count; i++)
  446. {
  447. int Chazhi = (ListValues[i - 1].Area - ListValues[i].Area);
  448. if (Chazhi > MaxChazhi*10)
  449. {
  450. MaxChazhi = Chazhi;
  451. ChazhiId = i;
  452. }
  453. }
  454. if(ChazhiId == -1)
  455. return;
  456. int yuzhi = (int)Math.Sqrt(2) + 2;
  457. }
  458. }
  459. public ParaTrainResultClass ParameterTrain()
  460. {
  461. var ListValues = shuLiClass.GetHistoryActive();
  462. ParaTrainResultClass Result = new ParaTrainResultClass();
  463. if (ListValues.Count() > 0)
  464. {
  465. if (ListValues.Count() > 500)
  466. {
  467. ListValues = ListValues.Skip(ListValues.Count - 500).OrderByDescending(o => o.Area).ToList();
  468. }
  469. if (ListValues.Count < 2) return Result;
  470. int ChazhiId = -1;
  471. int MaxChazhi = 0;
  472. for (int i = 1; i < ListValues.Count; i++)
  473. {
  474. if ((ListValues[i - 1].Area*3 <= ListValues[i].Area))
  475. {
  476. int Chazhi = (ListValues[i - 1].Area - ListValues[i].Area);
  477. if (Chazhi > MaxChazhi)
  478. {
  479. MaxChazhi = Chazhi;
  480. ChazhiId = i;
  481. }
  482. }
  483. }
  484. if (ChazhiId != -1)
  485. {
  486. Result.NoiseFilterThreshold = ListValues[ChazhiId].Area>=200?200:(int)(ListValues[ChazhiId].Area * 1.1);
  487. }
  488. else
  489. {
  490. Result.NoiseFilterThreshold = 200;
  491. }
  492. if (Result.NoiseFilterThreshold != -1)
  493. {
  494. ListValues = ListValues.Where(o => o.Area >= Result.NoiseFilterThreshold).ToList();
  495. }
  496. Result.MaxArea = ListValues.Max(x => x.Area);
  497. Result.MinArea = ListValues.Min(x => x.Area);
  498. Result.MaxLength = ListValues.Max(x => x.MaxLength);
  499. Result.MinLength = ListValues.Min(x => x.MaxLength);
  500. }
  501. return Result;
  502. }
  503. #endregion
  504. #region 私有方法
  505. //bool IsFill = false;
  506. //bool IsXuanZhuanCloseFaMen = false;
  507. /// <summary>
  508. /// 每数完一粒识别线程执行的事件
  509. /// </summary>
  510. /// <param name="sender"></param>
  511. /// <param name="e"></param>
  512. private void Worker_OneGrainCompleted(object sender, ActiveObjectEventArgsClass e)
  513. {
  514. LOG.log("有活跃物体转换为了历史物体,回调事件被触发!", 6);
  515. LOG.log(string.Format("图像处理实例中的待识别图像缓存队列长度{0}", shuLiClass.ImageNum), 6);
  516. if (e.Actives.Where(o => o.StateCode == 7).Count() > 0)
  517. {
  518. stopwatch.Restart();
  519. _ShuLiState = false;
  520. }
  521. else if (stopwatch.ElapsedMilliseconds > 1000)
  522. {
  523. stopwatch.Stop();
  524. _ShuLiState = true;
  525. }
  526. //往数组中计数
  527. ushort result = new ushort();
  528. // 事件处理逻辑
  529. foreach (ActiveObjectClass oneActive in e.Actives)
  530. {
  531. Console.WriteLine(string.Format("输出当前颗粒信息,开始行:{0},结束行:{1},开始时间:{2}结束时间:{3},颗粒状态:{4},通道数:{5}",
  532. oneActive.StartLine, oneActive.LastSeenLine, oneActive.StartCheckTime.ToString("O"), oneActive.EndCheckTime.ToString("O"), oneActive.StateCode, oneActive.ChannelNO));
  533. LOG.log(string.Format("输出当前颗粒信息,开始行:{0},结束行:{1},开始时间:{2}结束时间:{3},颗粒状态:{4},通道数:{5}",
  534. oneActive.StartLine, oneActive.LastSeenLine, oneActive.StartCheckTime.ToString("O"), oneActive.EndCheckTime.ToString("O"), oneActive.StateCode, oneActive.ChannelNO), 6);
  535. if(actionMesSqliteDataClass!=null)
  536. {
  537. actionMesSqliteDataClass.InsertActiveObject(oneActive);
  538. }
  539. if (oneActive.StateCode != 7 && oneActive.ChannelNO != -1)
  540. {
  541. //单通道合格计数
  542. result |= (ushort)(1 << oneActive.ChannelNO);
  543. }
  544. else
  545. {
  546. //单通道不合格计数
  547. result |= (ushort)(1 << (8 + oneActive.ChannelNO));
  548. }
  549. }
  550. LOG.log("当前待发送队列数量:" + SendQueue.Count, 6);
  551. if(IsSend)
  552. {
  553. SendQueue.Enqueue(result);
  554. }
  555. }
  556. #endregion
  557. #region 线程方法
  558. /// <summary>
  559. /// 开启交换线程
  560. /// </summary>
  561. private void StartSwitchThread()
  562. {
  563. IsSwitch = true;
  564. SwitchIdentifyImageThread = new Thread(SwitchIdentifyImageProcess);
  565. SwitchIdentifyImageThread.Start();
  566. }
  567. /// <summary>
  568. /// 关闭交换线程
  569. /// </summary>
  570. private void StopSwitchThread()
  571. {
  572. try
  573. {
  574. // 标志位设为false
  575. IsSwitch = false;
  576. if (SwitchIdentifyImageThread != null && SwitchIdentifyImageThread.IsAlive)
  577. SwitchIdentifyImageThread.Join();
  578. }
  579. catch (Exception ex)
  580. {
  581. FaultLog.RecordErrorMessage("Start thread failed!, " + ex.Message);
  582. throw;
  583. }
  584. }
  585. /// <summary>
  586. /// 交换线程
  587. /// </summary>
  588. private void SwitchIdentifyImageProcess()
  589. {
  590. IFrameOut IFramedata = null;
  591. Stopwatch stopwatch = Stopwatch.StartNew();
  592. stopwatch.Start();
  593. while (IsSwitch)
  594. {
  595. if (stopwatch.ElapsedMilliseconds > 1000)
  596. {
  597. //Console.WriteLine("交换线程-图像处理实例中的待识别图像缓存队列长度{0}", shuLiClass.ImageNum);
  598. GC.Collect();
  599. stopwatch.Restart();
  600. }
  601. //Thread.Sleep(5);
  602. bool result = cameraClass.GetOnceImage(out IFramedata);
  603. if (result)
  604. {
  605. //Debug模式,不进行图像处理
  606. if (_IsDebug)
  607. {
  608. _images.Enqueue(IFramedata.Image);
  609. if (_images.Count > 5)
  610. {
  611. _images.TryDequeue(out IImage image);
  612. image.Dispose();
  613. }
  614. }
  615. if (IFramedata == null)
  616. continue;
  617. shuLiClass.SetOnceIdentifyImageData(IFramedata.Image);
  618. }
  619. else
  620. continue;
  621. IFramedata.Dispose();
  622. }
  623. stopwatch.Stop();
  624. }
  625. /// <summary>
  626. /// 启动发送消息线程
  627. /// </summary>
  628. private void StartSendBottLogicMessageThread()
  629. {
  630. try
  631. {
  632. if(!IsConnectModbus) return;
  633. //zmcauxClass.OpenZmcauxCard();
  634. timeBeginPeriod(1); // 设置为1ms精度
  635. IsSend = true;
  636. SendBottLogicMessageThread = new Thread(SendBottLogicMessageProcess);
  637. SendBottLogicMessageThread.Start();
  638. }
  639. catch (Exception ex)
  640. {
  641. FaultLog.RecordErrorMessage("Start thread failed!, " + ex.Message);
  642. throw;
  643. }
  644. }
  645. /// <summary>
  646. /// 停止发送消息线程
  647. /// </summary>
  648. private void StopSendBottLogicMessageThread()
  649. {
  650. try
  651. {
  652. // 标志位设为false
  653. IsSend = false;
  654. if (SendBottLogicMessageThread != null && SendBottLogicMessageThread.IsAlive)
  655. SendBottLogicMessageThread.Join();
  656. //if (modbusTcpClient != null) modbusTcpClient.Disconnect();
  657. }
  658. catch (Exception ex)
  659. {
  660. FaultLog.RecordErrorMessage("Start thread failed!, " + ex.Message);
  661. throw;
  662. }
  663. }
  664. /// <summary>
  665. /// 信息发送线程
  666. /// </summary>
  667. private void SendBottLogicMessageProcess()
  668. {
  669. //获取数据
  670. ushort sendMessage = 0;
  671. bool AllowTransfer = false;
  672. bool TransferDone = false;
  673. Stopwatch sw = Stopwatch.StartNew();
  674. while (IsSend)
  675. {
  676. //LOG.log("进入线程", 6);
  677. sw.Restart();
  678. sendMessage = new ushort();
  679. //读取装瓶状态
  680. AllowTransfer = false;
  681. TransferDone = false;
  682. bool[] ReadResult = modbusTcpClient.ReadCoilsRegister(slaveId: 1, startAddress: 11, numRegisters: 2);
  683. if (ReadResult == null)
  684. {
  685. continue;
  686. }
  687. AllowTransfer = ReadResult[1];
  688. TransferDone = ReadResult[0];
  689. //LOG.log(string.Format("读取值:AllowTransfer[0]:{0},TransferDone[1]:{1}", AllowTransfer, TransferDone), 6);
  690. //当允许写入且处于未写入的状态时
  691. if (AllowTransfer && !TransferDone)
  692. {
  693. if (SendQueue.Count() > 0)
  694. {
  695. if (!SendQueue.TryDequeue(out sendMessage))
  696. {
  697. FaultLog.RecordErrorMessage("MainThreadClass-SendBottLogicMessageProcess-SendQueue.TryDequeue failed!");
  698. }
  699. }
  700. if (sendMessage != 0)
  701. {
  702. //写入数据
  703. modbusTcpClient.WriteSingleRegister(slaveId: 1, registerAddress: 100, value: sendMessage);
  704. modbusTcpClient.WriteCoilsRegister(slaveId: 1, CoilsAddress: 11, values: true);
  705. }
  706. sw.Stop();
  707. FaultLog.RecordLogMessage(string.Format("sendMessage[1]:{0},此次写值耗时:{1}", sendMessage, sw.Elapsed),1);
  708. }
  709. Thread.Sleep(1);
  710. }
  711. }
  712. #endregion
  713. #region 外部函数
  714. [DllImport("winmm.dll")]
  715. static extern uint timeBeginPeriod(uint period);
  716. #endregion
  717. }
  718. }