MainThreadClass.cs 32 KB

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