MainThreadClass.cs 28 KB

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