MainThreadClass.cs 30 KB

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