MainThreadClass.cs 28 KB

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