MainThreadClass.cs 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460
  1. using CCDCount.DLL.AlarmTools;
  2. using CCDCount.DLL.CanBus;
  3. using CCDCount.DLL.SqlDataClass;
  4. using CCDCount.DLL.Tools;
  5. using CCDCount.MODEL.CameraClass;
  6. using CCDCount.MODEL.ConfigModel;
  7. using CCDCount.MODEL.ResultModel;
  8. using CCDCount.MODEL.ShuLiModel;
  9. using LogClass;
  10. using MvCameraControl;
  11. using System;
  12. using System.Collections.Concurrent;
  13. using System.Collections.Generic;
  14. using System.Data.Entity.Core.Common.CommandTrees.ExpressionBuilder;
  15. using System.Diagnostics;
  16. using System.Drawing;
  17. using System.Linq;
  18. using System.Runtime.InteropServices;
  19. using System.Threading;
  20. using System.Threading.Tasks;
  21. namespace CCDCount.DLL
  22. {
  23. public class MainThreadClass
  24. {
  25. #region 变量与实例
  26. private bool IsSwitch = false;
  27. public ShuLiClass shuLiClass = null;
  28. CameraClass cameraClass = new CameraClass();
  29. public ShuLiConfigClass shuLiConfig
  30. {
  31. get
  32. {
  33. return ConfigManager.Instance.SaveConfigModel.ShuLiConfigClass;
  34. }
  35. set
  36. {
  37. ConfigManager.Instance.SaveConfigModel.ShuLiConfigClass = value;
  38. }
  39. }
  40. public CameraConfig cameraConfig
  41. {
  42. get
  43. {
  44. return ConfigManager.Instance.SaveConfigModel.CameraConfig;
  45. }
  46. set
  47. {
  48. ConfigManager.Instance.SaveConfigModel.CameraConfig = value;
  49. }
  50. }
  51. public bool CameraConfigIsChange = false;
  52. public string BatchNumber = "";
  53. public int ThisCamerNo = -1;
  54. public double XCoefficient {
  55. get
  56. {
  57. shuLiClass.GetXYCoefficient(out double XCoefficient, out double YCoefficient);
  58. return XCoefficient;
  59. }
  60. set
  61. {
  62. shuLiClass.SetXCoefficient(value);
  63. }
  64. }
  65. public double YCoefficient {
  66. get
  67. {
  68. shuLiClass.GetXYCoefficient(out double XCoefficient, out double YCoefficient);
  69. return YCoefficient;
  70. }
  71. set
  72. {
  73. shuLiClass.SetYCoefficient(value);
  74. }
  75. }
  76. public bool CameraStatic { get { return _CameraStatic; } }
  77. private bool _CameraStatic = false;
  78. // 返回交换线程状态
  79. public bool CameraRunStatic { get { return IsSwitch; } }
  80. public bool CameraSendMessageStatic { get { return IsSend; } }
  81. public bool IsOpenLoadThread { get { return _IsOpenLoadThread; }}
  82. private bool _IsOpenLoadThread = false;
  83. public int HistoryActiveNum { get { return shuLiClass.HistoryActiveNum; } }
  84. public int OkHistoryNum { get { return shuLiClass.OkHistoryNum; } }
  85. public int NgHistoryNum { get { return shuLiClass.NgHistoryNum; } }
  86. // 数粒信息发送线程
  87. Thread SendBottLogicMessageThread = null;
  88. bool IsSend = false;
  89. // Modbus客户端实例
  90. public ModbusTcpClient modbusTcpClient = new ModbusTcpClient();
  91. // 颗粒结果待发送队列
  92. //ConcurrentQueue<ushort> SendQueue = new ConcurrentQueue<ushort>();
  93. ConcurrentQueue<TestSenMessage> SendQueue = new ConcurrentQueue<TestSenMessage>();
  94. ConcurrentQueue<CanSenMessage> CanSendQueue = new ConcurrentQueue<CanSenMessage>();
  95. /// <summary>
  96. /// 数粒状态计时器
  97. /// </summary>
  98. Stopwatch stopwatch = Stopwatch.StartNew();
  99. /// <summary>
  100. /// 数粒状态
  101. /// </summary>
  102. private bool _ShuLiState = true;
  103. public bool ShuLiState { get { return _ShuLiState; } }
  104. private bool _IsDebug = true;
  105. public bool IsDebug { get { return _IsDebug; } }
  106. private bool IsConnectModbus = false;
  107. public static ActionMesSqliteDataClass actionMesSqliteDataClass = null;
  108. ConcurrentQueue<IFrameOut> _images = new ConcurrentQueue<IFrameOut>();
  109. public string FormulationName { get; set; } = string.Empty;
  110. public bool IsLoadFormulation = false;
  111. private long lastframeNum = -1;
  112. #endregion
  113. #region 公共方法
  114. /// <summary>
  115. /// 设置ModbusTcpClient
  116. /// </summary>
  117. /// <param name="modbusTcpClient"></param>
  118. public void ConnectModbus(string ipAddress)
  119. {
  120. Task.Run(() =>
  121. {
  122. int i = 10;
  123. while(!modbusTcpClient.Connect(ipAddress)&&i>0)
  124. {
  125. IsConnectModbus = false;
  126. //SystemAlarm.AlarmAlert(AlarmMessageList.数粒通讯连接失败, $"Modbus通讯连接失败,目标IP:{ipAddress}", "DLL:MainThreadClass-ConnectModbus");
  127. SystemAlarm.AlarmAlert(AlarmMessageList.数粒通讯连接失败,
  128. $"Number counting communication connection failed, target IP:{ipAddress}",
  129. $"Modbus通讯连接失败,目标IP:{ipAddress}",
  130. "DLL:MainThreadClass-ConnectModbus");
  131. i--;
  132. Task.Delay(1000);
  133. }
  134. SystemAlarm.AlarmCancel(AlarmMessageList.数粒通讯连接失败);
  135. LOG.log("数粒通讯成功", 6);
  136. IsConnectModbus = true;
  137. });
  138. }
  139. /// <summary>
  140. /// 初始化构造方法
  141. /// </summary>
  142. /// <param name="configClass"></param>
  143. /// <param name="CameraConfig"></param>
  144. public MainThreadClass(ShuLiConfigClass configClass,CameraConfig CameraConfig)
  145. {
  146. shuLiConfig = configClass;
  147. cameraConfig = CameraConfig;
  148. // 数粒配置文件地址
  149. if (configClass!=null)
  150. {
  151. // 创建数粒对象(配置文件)
  152. shuLiClass = new ShuLiClass(shuLiConfig);
  153. }
  154. else
  155. {
  156. // 创建数粒对象(默认)
  157. shuLiClass = new ShuLiClass();
  158. }
  159. _IsOpenLoadThread = cameraConfig.IsOpenLoad;
  160. ThisCamerNo = cameraConfig.CamerNo;
  161. }
  162. /// <summary>
  163. /// 加载相机
  164. /// </summary>
  165. /// <returns></returns>
  166. public bool LoadCamera()
  167. {
  168. bool result = false;
  169. // 相机列表
  170. try
  171. {
  172. // 获取相机列表
  173. cameraClass.GetCameraList(out List<CameraInfoClass> list);
  174. if (list.Count == 0)
  175. {
  176. //FaultLog.RecordErrorMessage(string.Format("{0}:没有相机", "MainThreadClass-StartMianThread"));
  177. SystemAlarm.AlarmAlert(AlarmMessageList.未检测到相机,
  178. "No Camera",
  179. "没有相机",
  180. "DLL:MainThreadClass-LoadCamera");
  181. // 如果没有相机,则退出
  182. return result;
  183. }
  184. SystemAlarm.AlarmCancel(AlarmMessageList.未检测到相机);
  185. // 加载相机
  186. // cameraClass.LoadCamereDevice(list.First().DeviceSN);
  187. if (!cameraClass.LoadCamereDevice(cameraConfig))
  188. {
  189. //FaultLog.RecordErrorMessage(string.Format("{0}:相机加载失败", "MainThreadClass-StartMianThread"));
  190. SystemAlarm.AlarmAlert(AlarmMessageList.相机加载失败,
  191. "No LoadCamera",
  192. "相机加载失败",
  193. "DLL:MainThreadClass-LoadCamera");
  194. return result;
  195. }
  196. SystemAlarm.AlarmCancel(AlarmMessageList.相机加载失败);
  197. CameraConfigIsChange = false;
  198. }
  199. catch(Exception ex)
  200. {
  201. Console.WriteLine($"MainThreadClass-LoadCamera:加载相机失败: {ex.Message}");
  202. }
  203. return result;
  204. }
  205. /// <summary>
  206. /// 重新加载相机配置
  207. /// </summary>
  208. public void ReLoadCameraConfig()
  209. {
  210. if(CameraConfigIsChange)
  211. {
  212. CameraConfig OldcameraConfig = cameraClass.GetConfigValue();
  213. if(OldcameraConfig.CameraSNNum != cameraConfig.CameraSNNum)
  214. {
  215. cameraClass.LoadCamereDevice(cameraConfig);
  216. }
  217. else
  218. {
  219. cameraClass.ReLoadCameraConfig(cameraConfig);
  220. }
  221. }
  222. }
  223. /// <summary>
  224. /// 开始主线程
  225. /// </summary>
  226. public bool StartMianThread()
  227. {
  228. bool result = false;
  229. try
  230. {
  231. if (BatchNumber == "")
  232. {
  233. FaultLog.RecordErrorMessage($"Camera {cameraConfig.CamerNo} does not have a batch number, and it failed to start", "Dll:MainThreadClass-StartMianThread");
  234. return result;
  235. }
  236. //if (!IsConnectModbus)
  237. //{
  238. // FaultLog.RecordErrorMessage($"Camera {cameraConfig.CamerNo} does not have a PLC connection, resulting in startup failure", "Dll:MainThreadClass-StartMianThread");
  239. // return result;
  240. //}
  241. timeBeginPeriod(1); // 设置为1ms精度
  242. actionMesSqliteDataClass = new ActionMesSqliteDataClass($"{AppDomain.CurrentDomain.BaseDirectory}DATA\\ActiveObjectData\\Cam{cameraConfig.CamerNo}\\ActiveObjectData_{BatchNumber}.db");
  243. //actionMesSqliteDataClass = new ActionMesSqliteDataClass($"{AppDomain.CurrentDomain.BaseDirectory}DATA\\ActiveObjectData\\Cam{cameraConfig.CamerNo}\\ActiveObjectData20250827.db");
  244. actionMesSqliteDataClass.GetAllActionMinStartMaxEndLine(out int num, out int StartLine, out int EndLine);
  245. shuLiClass.InitCurrentLine(EndLine);
  246. shuLiClass.InitNum(num);
  247. shuLiClass.QueueSemaphore = new SemaphoreSlim(0);
  248. cameraClass.FrameGrabbedEvent += SwitchIdentifyImageEvent;
  249. IsSwitch = true;
  250. // 取图开启
  251. if (!cameraClass.StartCamera())
  252. {
  253. return result;
  254. }
  255. _CameraStatic = true;
  256. StartCanSendBottLogicMessageThread();
  257. // 为数粒算法的识别成功一粒回调函数添加方法
  258. //shuLiClass.WorkCompleted += Worker_OneGrainCompleted;
  259. shuLiClass.WorkCompleted += Worker_OneGrainCompletedUseCan;
  260. // 开启识别线程
  261. shuLiClass.StartIdentifyFuntion(cameraClass.GetCamereImageSize().Width);
  262. result = true;
  263. }
  264. catch(Exception ex)
  265. {
  266. Console.WriteLine($"MainThreadClass-StartMianThread:启动失败: {ex.Message}");
  267. }
  268. return result;
  269. }
  270. /// <summary>
  271. /// 停止主线程
  272. /// </summary>
  273. public bool StopMianThread()
  274. {
  275. bool result = false;
  276. try
  277. {
  278. // 数粒识别线程关闭
  279. shuLiClass.StopIdentifyFuntion();
  280. LOG.log("执行数粒识别线程关闭成功",6);
  281. _CameraStatic = false;
  282. //shuLiClass.WorkCompleted -= Worker_OneGrainCompleted;
  283. shuLiClass.WorkCompleted -= Worker_OneGrainCompletedUseCan;
  284. LOG.log("识别回调取消完成",6);
  285. // 相机取图关闭
  286. cameraClass.StopCamera();
  287. cameraClass.FrameGrabbedEvent -= SwitchIdentifyImageEvent;
  288. LOG.log("相机回调取消完成", 6);
  289. IsSwitch = false;
  290. StopSendBottLogicMessageThread();
  291. LOG.log("发送线程关闭完成", 6);
  292. result = true;
  293. actionMesSqliteDataClass.Dispose();
  294. LOG.log("批处理实例释放完成", 6);
  295. }
  296. catch(Exception ex)
  297. {
  298. LOG.error($"MainThreadClass-StopMianThread:停止失败: {ex.Message}");
  299. }
  300. return result;
  301. }
  302. /// <summary>
  303. /// 释放相机资源
  304. /// </summary>
  305. public void DisposeCamera()
  306. {
  307. cameraClass.StopCamera();
  308. cameraClass.DisPoseCamera();
  309. }
  310. /// <summary>
  311. /// 重加载相机
  312. /// </summary>
  313. /// <param name="CameraSN"></param>
  314. /// <returns></returns>
  315. public bool ReLoadCamera(string CameraSN)
  316. {
  317. bool result;
  318. result = cameraClass.ReLoadCameraDevice(CameraSN);
  319. if (result)
  320. {
  321. cameraConfig = cameraClass.GetConfigValue();
  322. }
  323. return result;
  324. }
  325. /// <summary>
  326. /// 获取显示用的图片数据
  327. /// </summary>
  328. /// <param name="ImageHeight"></param>
  329. /// <param name="Data"></param>
  330. public void GetShowImage(int ImageHeight,out Bitmap ImageData)
  331. {
  332. List<RowStartEndCol> RowsShowList = new List<RowStartEndCol>();
  333. ActiveObjectClass NewActive = shuLiClass.GetLastActive();
  334. if (NewActive == null)
  335. {
  336. LOG.log(string.Format("{0}:没有获取到数粒数据", "MainThreadClass-GetShowImage"));
  337. ImageData = GetNullShowImage(4096, ImageHeight);
  338. return;
  339. }
  340. List<ActiveObjectClass> Data = shuLiClass.GetHistoryActive().Where(o => o.LastSeenLine > NewActive.LastSeenLine - ImageHeight).ToList();
  341. Bitmap BitmapImage = new Bitmap(NewActive.ImageWidth, ImageHeight);
  342. if (Data.Count > 0)
  343. {
  344. int ThisImageStartLine = (int)Data.Max(o => o.LastSeenLine) - ImageHeight;
  345. using (Graphics g = Graphics.FromImage(BitmapImage))
  346. {
  347. g.Clear(Color.White);
  348. var redPen = new Pen(Color.Red, 1);
  349. var bluePen = new Pen(Color.FromArgb(0,146,255), 1);
  350. var GreenPen = new Pen(Color.SeaGreen, 5);
  351. using (Pen RedPan = new Pen(Color.Black, 5))
  352. {
  353. for (int i = 0; i < shuLiClass.ChannelsRoi.Count - 1; i++)
  354. {
  355. g.DrawLine(RedPan, new Point(shuLiClass.ChannelsRoi[i], 0), new Point(shuLiClass.ChannelsRoi[i], BitmapImage.Height));
  356. }
  357. }
  358. foreach (var item in Data)
  359. {
  360. int roix = item.MinStartCol - 5;
  361. int roiy = (int)(item.StartLine - ThisImageStartLine) - 5 < 0 ? 0 : (int)(item.StartLine - ThisImageStartLine) - 5;
  362. int roiheight = (int)(item.LastSeenLine - ThisImageStartLine - roiy) + 10;
  363. int roiwidth = item.MaxEndCol - item.MinStartCol + 10;
  364. g.DrawRectangle(GreenPen, new Rectangle(roix, roiy, roiwidth, roiheight));
  365. Font font = new Font("Arial", 20);
  366. g.DrawString(item.Num.ToString(), font, Brushes.Black, new Point(roix - 20*item.Num.ToString().Length, roiy - 20));
  367. foreach (var item1 in item.RowsData)
  368. {
  369. if((int)(item1.RowsCol - ThisImageStartLine)<0) continue;
  370. int yPos = (int)(item1.RowsCol - ThisImageStartLine);
  371. g.DrawLine(item.StateCode == 0 ? bluePen : redPen, new Point(item1.StartCol, yPos), new Point(item1.EndCol, yPos));
  372. }
  373. }
  374. }
  375. }
  376. ImageData = BitmapImage.Clone() as Bitmap;
  377. BitmapImage.Dispose();
  378. //GC.Collect();
  379. }
  380. public void GetShowImage(int ImageHeight, int ImageWidth , out Bitmap ImageData)
  381. {
  382. List<RowStartEndCol> RowsShowList = new List<RowStartEndCol>();
  383. ActiveObjectClass NewActive = shuLiClass.GetLastActive();
  384. if (NewActive == null)
  385. {
  386. LOG.log(string.Format("{0}:没有获取到数粒数据", "MainThreadClass-GetShowImage"));
  387. ImageData = GetNullShowImage(ImageWidth, ImageHeight);
  388. return;
  389. }
  390. List<ActiveObjectClass> Data = shuLiClass.GetHistoryActive().Where(o => o.StartLine > NewActive.StartLine - ImageHeight).ToList();
  391. Bitmap BitmapImage = new Bitmap(NewActive.ImageWidth, ImageHeight);
  392. if (Data.Count > 0)
  393. {
  394. int ThisImageStartLine = (int)Data.Max(o => o.LastSeenLine) - ImageHeight;
  395. using (Graphics g = Graphics.FromImage(BitmapImage))
  396. {
  397. g.Clear(Color.White);
  398. var redPen = new Pen(Color.Red, 1);
  399. var bluePen = new Pen(Color.FromArgb(0, 146, 255), 1);
  400. var GreenPen = new Pen(Color.SeaGreen, 5);
  401. using (Pen RedPan = new Pen(Color.Black, 5))
  402. {
  403. for (int i = 0; i < shuLiClass.ChannelsRoi.Count - 1; i++)
  404. {
  405. g.DrawLine(RedPan, new Point(shuLiClass.ChannelsRoi[i], 0), new Point(shuLiClass.ChannelsRoi[i], BitmapImage.Height));
  406. }
  407. }
  408. foreach (var item in Data)
  409. {
  410. int roix = item.MinStartCol - 5;
  411. int roiy = ImageHeight - (int)(item.LastSeenLine - ThisImageStartLine) - 5 < 0 ? 0 : ImageHeight - (int)(item.LastSeenLine - ThisImageStartLine) - 5;
  412. int roiheight = ImageHeight - (int)(item.StartLine - ThisImageStartLine) - roiy + 10;
  413. int roiwidth = item.MaxEndCol - item.MinStartCol + 10;
  414. g.DrawRectangle(GreenPen, new Rectangle(roix, roiy, roiwidth, roiheight));
  415. Font font = new Font("Arial", 20);
  416. g.DrawString(item.Num.ToString(), font, Brushes.Black, new Point(roix - 20 * item.Num.ToString().Length, roiy - 20));
  417. foreach (var item1 in item.RowsData)
  418. {
  419. if ((int)(item1.RowsCol - ThisImageStartLine) < 0) continue;
  420. int yPos = ImageHeight - (int)(item1.RowsCol - ThisImageStartLine);
  421. g.DrawLine(item.StateCode == 0 ? bluePen : redPen, new Point(item1.StartCol, yPos), new Point(item1.EndCol, yPos));
  422. }
  423. }
  424. }
  425. }
  426. ImageData = BitmapImage.Clone() as Bitmap;
  427. BitmapImage.Dispose();
  428. //GC.Collect();
  429. }
  430. /// <summary>
  431. /// 获取无数据的图片
  432. /// </summary>
  433. /// <param name="ImageWidth"></param>
  434. /// <param name="ImageHeight"></param>
  435. /// <param name="ImageData"></param>
  436. public Bitmap GetNullShowImage(int ImageWidth, int ImageHeight)
  437. {
  438. if(ImageWidth==0)
  439. {
  440. return null;
  441. }
  442. Bitmap BitmapImage = new Bitmap(ImageWidth, ImageHeight);
  443. using (Graphics g = Graphics.FromImage(BitmapImage))
  444. {
  445. g.Clear(Color.White);
  446. using (Pen RedPan = new Pen(Color.Black, 8))
  447. {
  448. for (int i = 0; i < shuLiClass.ChannelsRoi.Count - 1; i++)
  449. {
  450. g.DrawLine(RedPan, new Point(shuLiClass.ChannelsRoi[i], 0), new Point(shuLiClass.ChannelsRoi[i], BitmapImage.Height));
  451. }
  452. }
  453. }
  454. return BitmapImage;
  455. }
  456. /// <summary>
  457. /// 获取此刻的Config数据
  458. /// </summary>
  459. /// <param name="config"></param>
  460. public void GetAllConfigValue(out CameraConfig Camconfig,out ShuLiConfigClass shuLiConfig)
  461. {
  462. //判断是否加载了相机
  463. if(cameraClass.IsLoadCamera())
  464. {
  465. //获取已经加载的相机的配置
  466. cameraConfig = cameraClass.GetConfigValue();
  467. Camconfig = cameraConfig;
  468. }
  469. else
  470. {
  471. cameraConfig = new CameraConfig();
  472. Camconfig = cameraConfig;
  473. }
  474. //读取视觉配置
  475. shuLiConfig = shuLiClass.GetConfigValue();
  476. this.shuLiConfig = shuLiConfig;
  477. }
  478. /// <summary>
  479. /// 获取相机此刻的Config数据
  480. /// </summary>
  481. /// <param name="CameraConfig"></param>
  482. public CameraConfig GetCameraConfig()
  483. {
  484. CameraConfig result = null;
  485. //判断是否加载了相机
  486. if (cameraClass.IsLoadCamera())
  487. {
  488. //获取已经加载的相机的配置
  489. result = cameraClass.GetConfigValue();
  490. cameraConfig = result;
  491. }
  492. return result;
  493. }
  494. /// <summary>
  495. /// 保存所有Config
  496. /// </summary>
  497. public void SaveAllConfig()
  498. {
  499. shuLiClass.SaveConfig();
  500. }
  501. /// <summary>
  502. /// 获取相机连接状态
  503. /// </summary>
  504. /// <returns></returns>
  505. public bool GetCameraConnectStatic()
  506. {
  507. bool result = false;
  508. if(cameraClass != null)
  509. result = cameraClass.IsConnectCamera();
  510. return result;
  511. }
  512. /// <summary>
  513. /// 清除历史数据
  514. /// </summary>
  515. /// <returns></returns>
  516. public bool ClearHistoryActive()
  517. {
  518. bool result = false;
  519. if(shuLiClass != null)
  520. result = shuLiClass.ClearHistoryActive();
  521. return result;
  522. }
  523. public bool ClearSendQueue()
  524. {
  525. bool result = false;
  526. while(SendQueue.Count>0)
  527. {
  528. SendQueue.TryDequeue(out TestSenMessage testSen);
  529. }
  530. result = true;
  531. return result;
  532. }
  533. /// <summary>
  534. /// 获取过去一秒内颗粒数量
  535. /// </summary>
  536. /// <returns></returns>
  537. public int GetOneSecondActiveNum()
  538. {
  539. int result = 0;
  540. if(shuLiClass != null)
  541. result = shuLiClass.GetHistoryActive().Where(o=>o.EndCheckTime>DateTime.Now-TimeSpan.FromSeconds(1)).Count();
  542. return result;
  543. }
  544. /// <summary>
  545. /// 获取相机原图一张
  546. /// </summary>
  547. /// <returns></returns>
  548. public Bitmap GetCamImageOnce()
  549. {
  550. Bitmap result = null;
  551. if(_images.Count>0)
  552. {
  553. _images.TryDequeue(out IFrameOut image);
  554. if(image != null)
  555. result = image.Image.ToBitmap();
  556. }
  557. return result;
  558. }
  559. public void ParameterTrain(List<ActiveObjectClass> ListValues)
  560. {
  561. if(ListValues.Count() > 0)
  562. {
  563. if(ListValues.Count()>500)
  564. {
  565. ListValues = ListValues.Take(500).OrderByDescending(o=>o.Area).ToList();
  566. }
  567. int MaxArea = ListValues.Max(x => x.Area);
  568. int MinArea = ListValues.Min(x => x.Area);
  569. double MaxLength = ListValues.Max(x => x.MaxLength);
  570. double MinLength = ListValues.Min(x => x.MaxLength);
  571. if(ListValues.Count<2) return;
  572. int ChazhiId = -1;
  573. int MaxChazhi = 0;
  574. for (int i = 1; i < ListValues.Count; i++)
  575. {
  576. int Chazhi = (ListValues[i - 1].Area - ListValues[i].Area);
  577. if (Chazhi > MaxChazhi*10)
  578. {
  579. MaxChazhi = Chazhi;
  580. ChazhiId = i;
  581. }
  582. }
  583. if(ChazhiId == -1)
  584. return;
  585. int yuzhi = (int)Math.Sqrt(2) + 2;
  586. }
  587. }
  588. /// <summary>
  589. /// 运行参数训练
  590. /// </summary>
  591. /// <returns></returns>
  592. public ParaTrainResultClass ParameterTrain()
  593. {
  594. var ListValues = shuLiClass.GetHistoryActive();
  595. ParaTrainResultClass Result = new ParaTrainResultClass();
  596. if (ListValues.Count() > 0)
  597. {
  598. if (ListValues.Count() > 500)
  599. {
  600. ListValues = ListValues.Skip(ListValues.Count - 500).OrderByDescending(o => o.Area).ToList();
  601. }
  602. if (ListValues.Count < 2)
  603. {
  604. Result = null;
  605. return Result;
  606. }
  607. Result.NoiseFilterThreshold = 5;
  608. var LengthListValues = ListValues.OrderBy(o => o.MaxLength).Skip(100).Take(300).ToList();
  609. Result.MaxLength = Convert.ToInt32(ListValues.Max(x => x.MaxLength) * 1.1);
  610. Result.MinLength = Convert.ToInt32(ListValues.Min(x => x.MaxLength) * 0.9);
  611. var AreaListValues = ListValues.OrderBy(o => o.Area).Skip(100).Take(300).ToList();
  612. Result.MaxArea = Convert.ToInt32(ListValues.Max(x => x.Area) * 1.1);
  613. Result.MinArea = Convert.ToInt32(ListValues.Min(x => x.Area) * 0.9);
  614. }
  615. return Result;
  616. }
  617. public ParaTrainResultClass ParameterTrain(int KeliW,int KeliL)
  618. {
  619. var ListValues = shuLiClass.GetHistoryActive();
  620. ParaTrainResultClass Result = new ParaTrainResultClass();
  621. List<ActiveObjectClass> LengthListValues = null;
  622. List<ActiveObjectClass> AreaListValues = null;
  623. if (ListValues.Count() > 0)
  624. {
  625. try
  626. {
  627. LOG.log("参数训练-数据筛选", 6);
  628. if (ListValues.Count() > 1000)
  629. {
  630. ListValues = ListValues.Skip(ListValues.Count - 1000).OrderByDescending(o => o.Num).ToList();
  631. }
  632. if (ListValues.Count < 2)
  633. {
  634. Result = null;
  635. return Result;
  636. }
  637. List<MaxLengthModel> maxLengthModels = new List<MaxLengthModel>();
  638. LOG.log("参数训练-凸包计算-未标定长度检测", 6);
  639. foreach (var item in ListValues)
  640. {
  641. List<Point> points = shuLiClass.ConvexHull(item.RowsData);
  642. var itemLenValue = shuLiClass.CoefficientCalculateMinimumBoundingRectangle(points);
  643. var UseValue = new MaxLengthModel()
  644. {
  645. MaxLength = itemLenValue.Height,
  646. Point1 = itemLenValue.HeightPoints[0],
  647. Point2 = itemLenValue.HeightPoints[1]
  648. };
  649. maxLengthModels.Add(UseValue);
  650. }
  651. LOG.log("参数训练-标定计算", 6);
  652. var ScaleResult = LineScanCameraCalibrator.CalculateLineScanPixelScale(maxLengthModels, KeliL);
  653. shuLiClass.SetXCoefficient(ScaleResult.XScale);
  654. shuLiClass.SetYCoefficient(ScaleResult.YScale);
  655. shuLiConfig.ScaleX = ScaleResult.XScale;
  656. shuLiConfig.ScaleY = ScaleResult.YScale;
  657. Result.ScaleX = ScaleResult.XScale;
  658. Result.ScaleY = ScaleResult.YScale;
  659. Result.NoiseFilterThreshold = 5;
  660. LOG.log("参数训练-计算标定后的长度", 6);
  661. foreach (var item in ListValues)
  662. {
  663. item.MaxLength = shuLiClass.SizeCalculation(item.RowsData).Height;
  664. }
  665. LOG.log("参数训练-长度数据筛选", 6);
  666. if (ListValues.Count >= 1000)
  667. {
  668. LengthListValues = ListValues.OrderBy(o => o.MaxLength).Skip(10).Take(980).ToList();
  669. }
  670. else
  671. {
  672. LengthListValues = ListValues.OrderBy(o => o.MaxLength).Skip(10).Take(ListValues.Count - 20).ToList();
  673. }
  674. LOG.log("参数训练-长度数据计算", 6);
  675. Result.MaxLength = Convert.ToInt32(LengthListValues.Max(x => x.MaxLength)) + 2;
  676. Result.MinLength = Convert.ToInt32(LengthListValues.Min(x => x.MaxLength) - 2);
  677. LOG.log("参数训练-面积数据筛选", 6);
  678. if (ListValues.Count >= 1000)
  679. {
  680. AreaListValues = ListValues.OrderBy(o => o.Area).Skip(10).Take(980).ToList();
  681. }
  682. else
  683. {
  684. AreaListValues = ListValues.OrderBy(o => o.Area).Skip(10).Take(ListValues.Count - 20).ToList();
  685. }
  686. LOG.log("参数训练-面积数据计算", 6);
  687. Result.MaxArea = Convert.ToInt32(AreaListValues.Max(x => x.Area)) + 50;
  688. Result.MinArea = Convert.ToInt32(AreaListValues.Min(x => x.Area)) - 50;
  689. }
  690. catch(Exception ex)
  691. {
  692. LOG.error(ex.Message);
  693. }
  694. }
  695. return Result;
  696. }
  697. #endregion
  698. #region 私有方法
  699. public DateTime FromUnixTimestamp(long timestamp, bool isMilliseconds = false)
  700. {
  701. try
  702. {
  703. // 如果未指定单位,尝试自动检测
  704. if (!isMilliseconds)
  705. {
  706. // 如果时间戳看起来像毫秒级(13位数字)
  707. if (timestamp.ToString().Length > 10)
  708. {
  709. isMilliseconds = true;
  710. }
  711. }
  712. if (isMilliseconds)
  713. {
  714. // 验证毫秒级时间戳范围
  715. const long minMilliTimestamp = -62135596800000; // 0001-01-01 00:00:00 UTC
  716. const long maxMilliTimestamp = 253402300799999; // 9999-12-31 23:59:59 UTC
  717. if (timestamp < minMilliTimestamp || timestamp > maxMilliTimestamp)
  718. {
  719. throw new ArgumentOutOfRangeException(nameof(timestamp),
  720. "毫秒级时间戳超出有效范围");
  721. }
  722. DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(timestamp);
  723. return TimeZoneInfo.ConvertTimeFromUtc(origin, TimeZoneInfo.Local);
  724. }
  725. else
  726. {
  727. // 验证秒级时间戳范围
  728. const long minTimestamp = -62135596800;
  729. const long maxTimestamp = 253402300799;
  730. if (timestamp < minTimestamp || timestamp > maxTimestamp)
  731. {
  732. throw new ArgumentOutOfRangeException(nameof(timestamp),
  733. "秒级时间戳超出有效范围");
  734. }
  735. DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddSeconds(timestamp);
  736. return TimeZoneInfo.ConvertTimeFromUtc(origin, TimeZoneInfo.Local);
  737. }
  738. }
  739. catch (ArgumentOutOfRangeException)
  740. {
  741. throw;
  742. }
  743. catch (Exception ex)
  744. {
  745. throw new ArgumentException($"无法转换时间戳 {timestamp}: {ex.Message}", ex);
  746. }
  747. }
  748. //bool IsFill = false;
  749. //bool IsXuanZhuanCloseFaMen = false;
  750. /// <summary>
  751. /// 每数完一粒识别线程执行的事件
  752. /// </summary>
  753. /// <param name="sender"></param>
  754. /// <param name="e"></param>
  755. private void Worker_OneGrainCompleted(object sender, ActiveObjectEventArgsClass e)
  756. {
  757. //LOG.log("有活跃物体转换为了历史物体,回调事件被触发!", 6);
  758. //LOG.log(string.Format("图像处理实例中的待识别图像缓存队列长度{0}", shuLiClass.ImageNum), 6);
  759. if (e.Actives.Where(o => o.StateCode == 7).Count() > 0)
  760. {
  761. stopwatch.Restart();
  762. _ShuLiState = false;
  763. }
  764. else if (stopwatch.ElapsedMilliseconds > 1000)
  765. {
  766. stopwatch.Stop();
  767. _ShuLiState = true;
  768. }
  769. //Int16 result = new Int16();
  770. ushort[] result = new ushort[2];
  771. var Hset = new HashSet<int>();
  772. // 事件处理逻辑
  773. foreach (ActiveObjectClass oneActive in e.Actives)
  774. {
  775. //往数组中计数
  776. var UseTime = (oneActive.EndCheckTime - oneActive.StartCheckTime).TotalMilliseconds;
  777. var QutuYanshiTime = (DateTime.Now - oneActive.PictureEndReadTime).TotalMilliseconds;
  778. if (BatchNumber!="") oneActive.BatchNumber = BatchNumber;
  779. LOG.log(string.Format("输出当前颗粒信息,颗粒编号:{0},开始时间:{1},第一张图像读取时间:{2},\n" +
  780. "识别耗时:{3},尾图到输出的时间:{4},颗粒状态:{5},通道数:{6}",
  781. oneActive.Num, oneActive.StartCheckTime.ToString("O"), oneActive.PictureStartReadTime.ToString("O"),
  782. UseTime.ToString(), QutuYanshiTime.ToString(), oneActive.StateCode, oneActive.ChannelNO), 6);
  783. if (QutuYanshiTime > 30)
  784. {
  785. //LOG.error($"结果输出延时超过了30ms,耗时{QutuYanshiTime}");
  786. Console.WriteLine($"结果输出延时超过了30ms,耗时{QutuYanshiTime}");
  787. }
  788. switch (oneActive.StateCode)
  789. {
  790. case 1:
  791. SystemAlarm.AlarmAlert(AlarmMessageList.数粒超长粒,
  792. "Counting extra-long particles",
  793. "数粒超长粒",
  794. "MianThreadClass-Worker_OneGrainCompleted");
  795. break;
  796. case 2:
  797. SystemAlarm.AlarmAlert(AlarmMessageList.数粒超短粒,
  798. "Counting ultra-short particles",
  799. "数粒超短粒",
  800. "MianThreadClass-Worker_OneGrainCompleted");
  801. break;
  802. case 5:
  803. SystemAlarm.AlarmAlert(AlarmMessageList.数粒超大粒,
  804. "Counting extra-large particles",
  805. "数粒超大粒",
  806. "MianThreadClass-Worker_OneGrainCompleted");
  807. break;
  808. case 6:
  809. SystemAlarm.AlarmAlert(AlarmMessageList.数粒超小粒,
  810. "Counting ultra-small particles",
  811. "数粒超小粒",
  812. "MianThreadClass-Worker_OneGrainCompleted");
  813. break;
  814. case 8:
  815. SystemAlarm.AlarmAlert(AlarmMessageList.疑似叠粒,
  816. "Count overlapping particles",
  817. "疑似叠粒",
  818. "MianThreadClass-Worker_OneGrainCompleted");
  819. break;
  820. case 10:
  821. SystemAlarm.AlarmAlert(AlarmMessageList.丢帧颗粒,
  822. "Counting frame loss particles",
  823. "丢帧颗粒",
  824. "MianThreadClass-Worker_OneGrainCompleted");
  825. break;
  826. }
  827. //记录到数据库
  828. ThreadPool.QueueUserWorkItem(_ =>
  829. {
  830. if (actionMesSqliteDataClass != null)
  831. {
  832. try
  833. {
  834. actionMesSqliteDataClass.AddData(oneActive);
  835. }
  836. catch (Exception ex)
  837. {
  838. LOG.error("MianThread-Worker_OneGrainCompleted-Task:" + ex.Message);
  839. }
  840. }
  841. });
  842. if (!Hset.Add(oneActive.ChannelNO))
  843. {
  844. //有重复的通道的异常记录流程
  845. var EResult = new ushort[2];
  846. //正常运行流程
  847. if (oneActive.ChannelNO == -1)
  848. {
  849. //FaultLog.RecordErrorMessage("颗粒通道判定异常");
  850. FaultLog.RecordErrorMessage("Abnormal particle channel determination");
  851. continue;
  852. }
  853. if (oneActive.StateCode == 0)
  854. {
  855. //单通道合格计数
  856. EResult[0] |= (ushort)(1 << oneActive.ChannelNO);
  857. }
  858. else
  859. {
  860. if (oneActive.StateCode != 7 && oneActive.StateCode != 9)
  861. {
  862. //单通道不合格计数
  863. EResult[1] |= (ushort)(1 << (oneActive.ChannelNO));
  864. }
  865. else if (oneActive.StateCode == 7)
  866. {
  867. //FaultLog.RecordErrorMessage("视野存在遮挡,请检查相机");
  868. FaultLog.RecordErrorMessage("The field of view is obstructed. Please check the camera");
  869. }
  870. }
  871. //SendQueue.Enqueue(new TestSenMessage()
  872. //{
  873. // Message = EResult,
  874. // NumMessage = new ushort[] { (ushort)oneActive.Num },
  875. // count = 1
  876. //});
  877. continue;
  878. }
  879. else
  880. {
  881. //正常运行流程
  882. if (oneActive.ChannelNO == -1)
  883. {
  884. //FaultLog.RecordErrorMessage("颗粒通道判定异常");
  885. FaultLog.RecordErrorMessage("Abnormal particle channel determination");
  886. continue;
  887. }
  888. if (oneActive.StateCode == 0)
  889. {
  890. //单通道合格计数
  891. result[0] |= (ushort)(1 << oneActive.ChannelNO);
  892. }
  893. else
  894. {
  895. if (oneActive.StateCode != 7 && oneActive.StateCode != 9)
  896. {
  897. //单通道不合格计数
  898. result[1] |= (ushort)(1 << (oneActive.ChannelNO));
  899. }
  900. else if (oneActive.StateCode == 7)
  901. {
  902. //FaultLog.RecordErrorMessage("视野存在遮挡,请检查相机");
  903. FaultLog.RecordErrorMessage("The field of view is obstructed. Please check the camera");
  904. }
  905. }
  906. }
  907. }
  908. //LOG.log("当前待发送队列数量:" + SendQueue.Count, 6);
  909. if (IsSend)
  910. {
  911. SendQueue.Enqueue(new TestSenMessage()
  912. {
  913. Message = result,
  914. //NumMessage = new ushort[] { (ushort)oneActive.Num },
  915. NumMessage = e.Actives.Select(o => (ushort)o.Num).ToArray(),
  916. count = (ushort)e.Actives.Count
  917. });
  918. }
  919. }
  920. /// <summary>
  921. /// 每数完一粒识别线程执行的事件
  922. /// </summary>
  923. /// <param name="sender"></param>
  924. /// <param name="e"></param>
  925. private void Worker_OneGrainCompletedUseCan(object sender, ActiveObjectEventArgsClass e)
  926. {
  927. //LOG.log("有活跃物体转换为了历史物体,回调事件被触发!", 6);
  928. //LOG.log(string.Format("图像处理实例中的待识别图像缓存队列长度{0}", shuLiClass.ImageNum), 6);
  929. if (e.Actives.Where(o => o.StateCode == 7).Count() > 0)
  930. {
  931. stopwatch.Restart();
  932. _ShuLiState = false;
  933. }
  934. else if (stopwatch.ElapsedMilliseconds > 1000)
  935. {
  936. stopwatch.Stop();
  937. _ShuLiState = true;
  938. }
  939. var Hset = new HashSet<int>();
  940. byte result = new byte();
  941. bool IsOK = false;
  942. // 事件处理逻辑
  943. foreach (ActiveObjectClass oneActive in e.Actives)
  944. {
  945. //往数组中计数
  946. var UseTime = (oneActive.EndCheckTime - oneActive.StartCheckTime).TotalMilliseconds;
  947. var QutuYanshiTime = (DateTime.Now - oneActive.PictureEndReadTime).TotalMilliseconds;
  948. if (BatchNumber != "") oneActive.BatchNumber = BatchNumber;
  949. LOG.log(string.Format("输出当前颗粒信息,颗粒编号:{0},开始时间:{1},第一张图像读取时间:{2},\n" +
  950. "识别耗时:{3},尾图到输出的时间:{4},颗粒状态:{5},通道数:{6}",
  951. oneActive.Num, oneActive.StartCheckTime.ToString("O"), oneActive.PictureStartReadTime.ToString("O"),
  952. UseTime.ToString(), QutuYanshiTime.ToString(), oneActive.StateCode, oneActive.ChannelNO), 6);
  953. if (QutuYanshiTime > 30)
  954. {
  955. //LOG.error($"结果输出延时超过了30ms,耗时{QutuYanshiTime}");
  956. Console.WriteLine($"结果输出延时超过了30ms,耗时{QutuYanshiTime}");
  957. }
  958. switch (oneActive.StateCode)
  959. {
  960. case 1:
  961. SystemAlarm.AlarmAlert(AlarmMessageList.数粒超长粒,
  962. "Counting extra-long particles",
  963. "数粒超长粒",
  964. "MianThreadClass-Worker_OneGrainCompleted");
  965. break;
  966. case 2:
  967. SystemAlarm.AlarmAlert(AlarmMessageList.数粒超短粒,
  968. "Counting ultra-short particles",
  969. "数粒超短粒",
  970. "MianThreadClass-Worker_OneGrainCompleted");
  971. break;
  972. case 5:
  973. SystemAlarm.AlarmAlert(AlarmMessageList.数粒超大粒,
  974. "Counting extra-large particles",
  975. "数粒超大粒",
  976. "MianThreadClass-Worker_OneGrainCompleted");
  977. break;
  978. case 6:
  979. SystemAlarm.AlarmAlert(AlarmMessageList.数粒超小粒,
  980. "Counting ultra-small particles",
  981. "数粒超小粒",
  982. "MianThreadClass-Worker_OneGrainCompleted");
  983. break;
  984. case 8:
  985. SystemAlarm.AlarmAlert(AlarmMessageList.疑似叠粒,
  986. "Count overlapping particles",
  987. "疑似叠粒",
  988. "MianThreadClass-Worker_OneGrainCompleted");
  989. break;
  990. case 10:
  991. SystemAlarm.AlarmAlert(AlarmMessageList.丢帧颗粒,
  992. "Counting frame loss particles",
  993. "丢帧颗粒",
  994. "MianThreadClass-Worker_OneGrainCompleted");
  995. break;
  996. }
  997. //记录到数据库
  998. ThreadPool.QueueUserWorkItem(_ =>
  999. {
  1000. if (actionMesSqliteDataClass != null)
  1001. {
  1002. try
  1003. {
  1004. actionMesSqliteDataClass.InsertActiveObject(oneActive);
  1005. }
  1006. catch (Exception ex)
  1007. {
  1008. LOG.error("MianThread-Worker_OneGrainCompleted-Task:" + ex.Message);
  1009. }
  1010. }
  1011. });
  1012. if (!Hset.Add(oneActive.ChannelNO))
  1013. {
  1014. //有重复的通道的异常记录流程
  1015. var EResult = new byte();
  1016. bool EIsOK = false;
  1017. //正常运行流程
  1018. if (oneActive.ChannelNO == -1)
  1019. {
  1020. //FaultLog.RecordErrorMessage("颗粒通道判定异常");
  1021. FaultLog.RecordErrorMessage("Abnormal particle channel determination");
  1022. continue;
  1023. }
  1024. if (oneActive.StateCode == 0)
  1025. {
  1026. //单通道合格计数
  1027. EResult |= (byte)(1 << oneActive.ChannelNO);
  1028. EIsOK = true;
  1029. }
  1030. else
  1031. {
  1032. if (oneActive.StateCode != 7 && oneActive.StateCode != 9)
  1033. {
  1034. //单通道不合格计数
  1035. EResult |= (byte)(1 << (oneActive.ChannelNO));
  1036. }
  1037. else if (oneActive.StateCode == 7)
  1038. {
  1039. //FaultLog.RecordErrorMessage("视野存在遮挡,请检查相机");
  1040. FaultLog.RecordErrorMessage("The field of view is obstructed. Please check the camera");
  1041. }
  1042. }
  1043. CanSendQueue.Enqueue(new CanSenMessage()
  1044. {
  1045. SendDate = EResult,
  1046. IsOK = EIsOK,
  1047. TaiHao = 0
  1048. });
  1049. continue;
  1050. }
  1051. else
  1052. {
  1053. //正常运行流程
  1054. if (oneActive.ChannelNO == -1)
  1055. {
  1056. //FaultLog.RecordErrorMessage("颗粒通道判定异常");
  1057. FaultLog.RecordErrorMessage("Abnormal particle channel determination");
  1058. continue;
  1059. }
  1060. if (oneActive.StateCode == 0)
  1061. {
  1062. //单通道合格计数
  1063. result |= (byte)(1 << oneActive.ChannelNO);
  1064. }
  1065. else
  1066. {
  1067. if (oneActive.StateCode != 7 && oneActive.StateCode != 9)
  1068. {
  1069. //单通道不合格计数
  1070. result |= (byte)(1 << (oneActive.ChannelNO));
  1071. }
  1072. else if (oneActive.StateCode == 7)
  1073. {
  1074. //FaultLog.RecordErrorMessage("视野存在遮挡,请检查相机");
  1075. FaultLog.RecordErrorMessage("The field of view is obstructed. Please check the camera");
  1076. }
  1077. }
  1078. }
  1079. }
  1080. if (IsSend)
  1081. {
  1082. CanSendQueue.Enqueue(new CanSenMessage()
  1083. {
  1084. SendDate = result,
  1085. IsOK = IsOK,
  1086. TaiHao = 0
  1087. });
  1088. }
  1089. }
  1090. #endregion
  1091. #region 线程方法
  1092. /// <summary>
  1093. /// 交换数据事件-赋予给相机回调方法
  1094. /// </summary>
  1095. /// <param name="sender"></param>
  1096. /// <param name="e"></param>
  1097. private void SwitchIdentifyImageEvent(object sender, FrameGrabbedEventArgs e)
  1098. {
  1099. if (e.FrameOut!=null)
  1100. {
  1101. //var QutuYanshiTime = (DateTime.Now - FromUnixTimestamp((long)e.FrameOut.HostTimeStamp)).TotalMilliseconds;
  1102. //if (QutuYanshiTime > 12)
  1103. //{
  1104. // Console.WriteLine($"GetOnceImage-识别延时超过了12ms,耗时{QutuYanshiTime}");
  1105. //}
  1106. if (lastframeNum == -1)
  1107. {
  1108. lastframeNum = e.FrameOut.FrameNum;
  1109. }
  1110. else if (lastframeNum == e.FrameOut.FrameNum - 1)
  1111. {
  1112. lastframeNum = e.FrameOut.FrameNum;
  1113. }
  1114. else
  1115. {
  1116. //丢帧记录
  1117. LOG.log(string.Format("lost frame: Width[{0}] , Height[{1}] , FrameNum[{2}] ,Frevous[{3}]",
  1118. e.FrameOut.Image.Width, e.FrameOut.Image.Height, e.FrameOut.FrameNum, lastframeNum), 6);
  1119. Console.WriteLine("lost frame: Width[{0}] , Height[{1}] , FrameNum[{2}] ,Frevous[{3}]",
  1120. e.FrameOut.Image.Width, e.FrameOut.Image.Height, e.FrameOut.FrameNum, lastframeNum);
  1121. lastframeNum = e.FrameOut.FrameNum;
  1122. }
  1123. //Debug模式,不进行图像处理
  1124. if (_IsDebug)
  1125. {
  1126. _images.Enqueue(e.FrameOut.Clone() as IFrameOut);
  1127. if (_images.Count > 5)
  1128. {
  1129. _images.TryDequeue(out IFrameOut image);
  1130. image.Dispose();
  1131. }
  1132. }
  1133. shuLiClass.SetOnceIdentifyImageData(e.FrameOut);
  1134. shuLiClass.QueueSemaphore.Release(); // 通知处理线程有新数据
  1135. }
  1136. e.FrameOut.Dispose();
  1137. }
  1138. /// <summary>
  1139. /// 启动发送消息线程
  1140. /// </summary>
  1141. private bool StartSendBottLogicMessageThread()
  1142. {
  1143. bool result = false;
  1144. try
  1145. {
  1146. if(!IsConnectModbus) return result;
  1147. IsSend = true;
  1148. SendBottLogicMessageThread = new Thread(SendBottLogicMessageProcess);
  1149. SendBottLogicMessageThread.Start();
  1150. SystemAlarm.AlarmCancel(AlarmMessageList.结果发送线程启动失败);
  1151. result = true;
  1152. }
  1153. catch (Exception ex)
  1154. {
  1155. //FaultLog.RecordErrorMessage("MianThread-StartSendBottLogicMessageThread:Start thread failed!, " + ex.Message);
  1156. SystemAlarm.AlarmAlert(AlarmMessageList.结果发送线程启动失败,
  1157. "MianThread-StartSendBottLogicMessageThread:Start thread failed!, " + ex.Message,
  1158. "结果发送线程启动失败," + ex.Message,
  1159. "DLL:MainThreadClass-StartSendBottLogicMessageThread");
  1160. Console.WriteLine("MianThread-StartSendBottLogicMessageThread:Start thread failed!, " + ex.Message);
  1161. result = false;
  1162. }
  1163. return result;
  1164. }
  1165. /// <summary>
  1166. /// 停止发送消息线程
  1167. /// </summary>
  1168. private void StopSendBottLogicMessageThread()
  1169. {
  1170. try
  1171. {
  1172. // 标志位设为false
  1173. if (SendBottLogicMessageThread != null && SendBottLogicMessageThread.IsAlive)
  1174. {
  1175. try
  1176. {
  1177. IsSend = false;
  1178. SendBottLogicMessageThread.Join();
  1179. //SendBottLogicMessageThread.Interrupt();
  1180. }
  1181. catch (ThreadStateException)
  1182. {
  1183. // 忽略异常
  1184. }
  1185. }
  1186. //if (modbusTcpClient != null) modbusTcpClient.Disconnect();
  1187. SystemAlarm.AlarmCancel(AlarmMessageList.结果发送线程停止失败);
  1188. }
  1189. catch (Exception ex)
  1190. {
  1191. //FaultLog.RecordErrorMessage("Start thread failed!, " + ex.Message);
  1192. SystemAlarm.AlarmAlert(AlarmMessageList.结果发送线程停止失败,
  1193. "MianThread-StopSendBottLogicMessageThread:Stop thread failed!, " + ex.Message,
  1194. "结果发送线程停止失败, " + ex.Message,
  1195. "DLL:MainThreadClass-StopSendBottLogicMessageThread");
  1196. throw;
  1197. }
  1198. }
  1199. /// <summary>
  1200. /// 启动发送消息线程
  1201. /// </summary>
  1202. private bool StartCanSendBottLogicMessageThread()
  1203. {
  1204. bool result = false;
  1205. try
  1206. {
  1207. IsSend = true;
  1208. SendBottLogicMessageThread = new Thread(SendBottLogicMessageProcessUseCan);
  1209. SendBottLogicMessageThread.Start();
  1210. SystemAlarm.AlarmCancel(AlarmMessageList.结果发送线程启动失败);
  1211. result = true;
  1212. }
  1213. catch (Exception ex)
  1214. {
  1215. //FaultLog.RecordErrorMessage("MianThread-StartSendBottLogicMessageThread:Start thread failed!, " + ex.Message);
  1216. SystemAlarm.AlarmAlert(AlarmMessageList.结果发送线程启动失败,
  1217. "MianThread-StartSendBottLogicMessageThread:Start thread failed!, " + ex.Message,
  1218. "结果发送线程启动失败," + ex.Message,
  1219. "DLL:MainThreadClass-StartSendBottLogicMessageThread");
  1220. Console.WriteLine("MianThread-StartSendBottLogicMessageThread:Start thread failed!, " + ex.Message);
  1221. result = false;
  1222. }
  1223. return result;
  1224. }
  1225. /// <summary>
  1226. /// 信息发送线程
  1227. /// </summary>
  1228. private void SendBottLogicMessageProcess()
  1229. {
  1230. //获取数据
  1231. TestSenMessage sendMessage;
  1232. Stopwatch sw = Stopwatch.StartNew();
  1233. Stopwatch WriteDoneTime = Stopwatch.StartNew();
  1234. ushort writedoneMes = 0;
  1235. writedoneMes |= (ushort)(1 << 0);
  1236. while (IsSend)
  1237. {
  1238. //LOG.log("进入线程", 6);
  1239. sendMessage = new TestSenMessage();
  1240. ushort[] ReturnValue = null;
  1241. ushort[] result = new ushort[20];
  1242. modbusTcpClient.ReadHoldingRegisters(slaveId: 1, startAddress: 0, numRegisters: 1, out ReturnValue);
  1243. if (ReturnValue == null)
  1244. {
  1245. continue;
  1246. }
  1247. if ((ReturnValue[0] & 1) == 0)
  1248. {
  1249. WriteDoneTime.Restart();
  1250. while (SendQueue.Count==0&& IsSend)
  1251. {
  1252. //Thread.Sleep(1);
  1253. }
  1254. sw.Restart();
  1255. int SendMessageCount = SendQueue.Count > 10 ? 10 : SendQueue.Count;
  1256. for (int i = 0; i < SendMessageCount; i++)
  1257. {
  1258. if (!SendQueue.TryDequeue(out sendMessage))
  1259. {
  1260. //FaultLog.RecordErrorMessage("MainThreadClass-SendBottLogicMessageProcess-SendQueue.TryDequeue failed!");
  1261. }
  1262. if (sendMessage.Message == null)
  1263. {
  1264. continue;
  1265. }
  1266. result[i * 2] = sendMessage.Message[0];
  1267. result[i * 2 + 1] = sendMessage.Message[1];
  1268. }
  1269. //写入数据
  1270. modbusTcpClient.WriteMultipleRegisters(slaveId: 1, startAddress: 100, values: result);
  1271. modbusTcpClient.WriteSingleRegister(slaveId: 1, registerAddress: 0, value: writedoneMes);
  1272. if (result[0] > 0 || result[1]>0)
  1273. {
  1274. sw.Stop();
  1275. WriteDoneTime.Stop();
  1276. LOG.log(string.Format("待发送数量{0}", SendQueue.Count), 6);
  1277. LOG.log(string.Format("SendMess1Ok:{0},SendMess1Ng:{1},SendMess2Ok:{2},SendMess2Ng:{3}," +
  1278. "\nSendMessage3Ok:{4},SendMessage3Ng:{5},SendMessage4Ok:{6},SendMessage4Ng:{7}," +
  1279. "\nSendMessage5Ok:{8},SendMessage5Ng:{9},SendMessage6Ok:{10},SendMessage6Ng:{11}," +
  1280. "\nSendMessage7Ok:{12},SendMessage7Ng:{13},SendMessage8Ok:{14},SendMessage8Ng:{15}," +
  1281. "\nSendMessage9Ok:{16},SendMessage9Ng:{17},SendMessage10Ok:{18},SendMessage10Ng:{19}," +
  1282. "\n此次写值耗时:{20},此次WriteDone耗时:{21},此次写入数据量{22}",
  1283. result[0], result[1], result[2], result[3],
  1284. result[4], result[5], result[6], result[7],
  1285. result[8], result[9], result[10], result[11],
  1286. result[12], result[13], result[14], result[15],
  1287. result[16], result[17], result[18], result[19],
  1288. sw.Elapsed,WriteDoneTime.Elapsed,sendMessage.count), 6);
  1289. if (sw.ElapsedMilliseconds > 10)
  1290. LOG.error("通讯超时");
  1291. }
  1292. }
  1293. Thread.Sleep(1);
  1294. }
  1295. }
  1296. private void SendBottLogicMessageProcessUseCan()
  1297. {
  1298. //获取数据
  1299. CanSenMessage sendMessage;
  1300. Stopwatch sw = Stopwatch.StartNew();
  1301. Stopwatch WriteDoneTime = Stopwatch.StartNew();
  1302. CanManagerClass canManager = new CanManagerClass();
  1303. bool isFrist = true;
  1304. try
  1305. {
  1306. canManager.OpenDevice();
  1307. canManager.InitCan();
  1308. }
  1309. catch (Exception ex)
  1310. {
  1311. LOG.error(string.Format("MainThreadClass-SendBottLogicMessageProcessUseCan-Open:{0}", ex.Message));
  1312. }
  1313. while (IsSend)
  1314. {
  1315. try
  1316. {
  1317. //LOG.log("进入线程", 6);
  1318. sendMessage = new CanSenMessage();
  1319. bool IsTrigger = canManager.GetTrigger(ref isFrist);
  1320. if (!IsTrigger)
  1321. {
  1322. continue;
  1323. }
  1324. else
  1325. {
  1326. WriteDoneTime.Restart();
  1327. while (CanSendQueue.Count == 0 && IsSend)
  1328. {
  1329. Thread.Sleep(1);
  1330. }
  1331. sw.Restart();
  1332. if (!CanSendQueue.TryDequeue(out sendMessage))
  1333. {
  1334. FaultLog.RecordErrorMessage("MainThreadClass-SendBottLogicMessageProcess-SendQueue.TryDequeue failed!");
  1335. }
  1336. canManager.SenMessage(sendMessage);
  1337. }
  1338. }
  1339. catch (Exception ex)
  1340. {
  1341. LOG.error(string.Format("MainThreadClass-SendBottLogicMessageProcessUseCan-Send:{0}", ex.Message));
  1342. }
  1343. }
  1344. try
  1345. {
  1346. canManager.CloseCan();
  1347. }
  1348. catch (Exception ex)
  1349. {
  1350. LOG.error(string.Format("MainThreadClass-SendBottLogicMessageProcessUseCan-Close:{0}", ex.Message));
  1351. }
  1352. LOG.log("发送线程关闭完成", 6);
  1353. }
  1354. #endregion
  1355. #region 外部函数
  1356. [DllImport("winmm.dll")]
  1357. static extern uint timeBeginPeriod(uint period);
  1358. #endregion
  1359. }
  1360. public class TestSenMessage
  1361. {
  1362. public ushort[] Message { get; set; }
  1363. //public Int16 Message { get; set; }
  1364. public ushort[] NumMessage { get; set; }
  1365. public ushort count { get; set; }
  1366. }
  1367. public class CanSenMessage
  1368. {
  1369. public byte SendDate { get; set; }
  1370. public bool IsOK { get; set; }
  1371. public int TaiHao { get; set; }
  1372. }
  1373. }