MainThreadClass.cs 33 KB

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