MainThreadClass.cs 30 KB

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