MainThreadClass.cs 54 KB

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