MainThreadClass.cs 42 KB

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