Management.cs 134 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904
  1. using Basler.Pylon;
  2. using Cognex.VisionPro;
  3. using Cognex.VisionPro.ToolBlock;
  4. using ControlzEx.Standard;
  5. using CSScripting;
  6. using MathNet.Numerics.Distributions;
  7. using MathNet.Numerics.LinearAlgebra;
  8. using MathNet.Numerics.RootFinding;
  9. using NPOI.SS.Formula.Functions;
  10. using NPOI.Util;
  11. using Opc.Ua;
  12. using OpenCvSharp;
  13. using OpenCvSharp.Flann;
  14. using Org.BouncyCastle.Crypto;
  15. using Prism.Events;
  16. using Prism.Ioc;
  17. using Prism.Mvvm;
  18. using Prism.Regions;
  19. using Prism.Services.Dialogs;
  20. using SqlSugar;
  21. using System;
  22. using System.Collections;
  23. using System.Collections.Generic;
  24. using System.Collections.ObjectModel;
  25. using System.ComponentModel;
  26. using System.Diagnostics;
  27. using System.Drawing;
  28. using System.IO;
  29. using System.Linq;
  30. using System.Net.Sockets;
  31. using System.Reflection.Metadata;
  32. using System.Security.Cryptography;
  33. using System.Text;
  34. using System.Threading;
  35. using System.Threading.Tasks;
  36. using System.Windows;
  37. using System.Windows.Documents;
  38. using System.Windows.Interop;
  39. using System.Windows.Media;
  40. using System.Windows.Media.Media3D;
  41. using Team.FFFeederService;
  42. using Team.FFFeederService.Interfaces;
  43. using TeamAAS_VP;
  44. using TeamAAS_VP.Core.PLCs;
  45. using TeamAAS_VP.Core.Robots;
  46. using TeamAAS_VP.Core.ScrewDriver;
  47. using TeamAAS_VP.Data;
  48. using TeamAAS_VP.Enums;
  49. using TeamAAS_VP.Events;
  50. using TeamAAS_VP.Interfaces;
  51. using TeamAAS_VP.Models;
  52. using TeamAAS_VP.Models.Calibration;
  53. using TeamAAS_VP.Models.Feeder;
  54. using TeamAAS_VP.Models.PLC;
  55. using TeamAAS_VP.Models.Product;
  56. using TeamAAS_VP.Resources.Languages;
  57. using TeamAAS_VP.Services;
  58. using TeamAAS_VP.ViewModels;
  59. using TeamAAS_VP.ViewModels.Home;
  60. using TouchSocket.Core;
  61. using TouchSocket.Sockets;
  62. using static MaterialDesignThemes.Wpf.Theme.ToolBar;
  63. using static Org.BouncyCastle.Math.EC.ECCurve;
  64. using static System.Windows.Forms.AxHost;
  65. namespace TeamAAS_VP.Core
  66. {
  67. public class Management : BindableBase
  68. {
  69. #region 字段
  70. IRegionManager _regionManager;
  71. IEventAggregator _eventAggregator;
  72. IContainerProvider _container;
  73. IConfigService _configService;
  74. IRobotService _robotService;
  75. IScannerService _scannerService;
  76. ICameraService _cameraService;
  77. IFeederService _feederService;
  78. IPlcService _plcService;
  79. ILightManagerService _lightManagerService;
  80. IProductService _productService;
  81. ICalibrationService _calibrationService;
  82. IRemoteCommandService _remoteCommandService;
  83. ISystemDatabaseService _systemDatabaseService;
  84. IMesService _mesService;
  85. Timer yieldtimer;
  86. private DateTime StartTime = DateTime.Now;
  87. /// <summary>
  88. /// 产品主sn
  89. /// </summary>
  90. string ProductMainSN = "";
  91. string wo = "";
  92. #endregion
  93. #region 属性
  94. public string[] CsvData = new string[50];
  95. public int[] ResultData = new int[200];
  96. public string code = "";
  97. List<LockResult> lockResultsAll = new List<LockResult>();//一个产品的总结果
  98. private ObservableCollection<ShowRender> _Renders;
  99. private double _CTtime;
  100. public int ResultDataCount;
  101. private bool _ShowMes_Query;
  102. /// <summary>
  103. /// 显示查询结果
  104. /// </summary>
  105. public bool ShowMes_Query
  106. {
  107. get { return _ShowMes_Query; }
  108. set { SetProperty(ref _ShowMes_Query, value); }
  109. }
  110. private bool _ShowMes_Result;
  111. /// <summary>
  112. /// 显示上传结果
  113. /// </summary>
  114. public bool ShowMes_Result
  115. {
  116. get { return _ShowMes_Result; }
  117. set { SetProperty(ref _ShowMes_Result, value); }
  118. }
  119. /// <summary>
  120. /// ct
  121. /// </summary>
  122. public double CTtime
  123. {
  124. get { return _CTtime; }
  125. set { SetProperty(ref _CTtime, value); }
  126. }
  127. /// <summary>
  128. /// 显示界面
  129. /// </summary>
  130. public ObservableCollection<ShowRender> Renders
  131. {
  132. get { return _Renders; }
  133. set { SetProperty(ref _Renders, value); }
  134. }
  135. private ProductModel _CurrentProduct;
  136. /// <summary>
  137. /// 当前产品
  138. /// </summary>
  139. public ProductModel CurrentProduct
  140. {
  141. get { return _CurrentProduct; }
  142. set { SetProperty(ref _CurrentProduct, value); }
  143. }
  144. public BgCommunicate BgCommunicate { get; private set; }
  145. public BgModbusTcpCommunicate BgModbusTcpCommunicate { get; private set; }
  146. private ObservableCollection<StatusInfo> _Status = new ObservableCollection<StatusInfo>();
  147. /// <summary>
  148. /// 状态栏集合
  149. /// </summary>
  150. public ObservableCollection<StatusInfo> Status
  151. {
  152. get { return _Status; }
  153. set { SetProperty(ref _Status, value); }
  154. }
  155. private Int64 _TotalQuantity;
  156. /// <summary>
  157. /// 总产量
  158. /// </summary>
  159. public Int64 TotalQuantity
  160. {
  161. get { return _TotalQuantity; }
  162. set { SetProperty(ref _TotalQuantity, value); }
  163. }
  164. private Int64 _TotalQuantityToday;
  165. /// <summary>
  166. /// 当天的总产量
  167. /// </summary>
  168. public Int64 TotalQuantityToday
  169. {
  170. get { return _TotalQuantityToday; }
  171. set { SetProperty(ref _TotalQuantityToday, value); }
  172. }
  173. private Int64 _CurrentUPH;
  174. /// <summary>
  175. /// 当前的UPH
  176. /// </summary>
  177. public Int64 CurrentUPH
  178. {
  179. get { return _CurrentUPH; }
  180. set { SetProperty(ref _CurrentUPH, value); }
  181. }
  182. private Int64 _NgNumber;
  183. /// <summary>
  184. /// 当前的NG数量
  185. /// </summary>
  186. public Int64 NgNumber
  187. {
  188. get { return _NgNumber; }
  189. set { SetProperty(ref _NgNumber, value); }
  190. }
  191. private double _Yield;
  192. /// <summary>
  193. /// 当前的NG数量
  194. /// </summary>
  195. public double Yield
  196. {
  197. get { return _Yield; }
  198. set { SetProperty(ref _Yield, value); }
  199. }
  200. private XYD_ScrewDriver _ScrewDriver;
  201. public XYD_ScrewDriver ScrewDriver
  202. {
  203. get { return _ScrewDriver; }
  204. set { SetProperty(ref _ScrewDriver, value); }
  205. }
  206. public Dictionary<string, object> BackupObject { get; set; } = new Dictionary<string, object>();
  207. #endregion
  208. #region 命令
  209. #endregion
  210. #region 事件
  211. #endregion
  212. public Management(IRegionManager regionManager, IEventAggregator ea, IContainerProvider container, IConfigService configService,
  213. IRobotService robotService, ICameraService cameraService, IFeederService feederService, IPlcService plcService, IProductService productService,
  214. ICalibrationService calibrationService, IRemoteCommandService remoteCommandService, ISystemDatabaseService systemDatabaseService, ILightManagerService lightManagerService, IMesService mesService, IScannerService scannerService)
  215. {
  216. _regionManager = regionManager;
  217. _eventAggregator = ea;
  218. _container = container;
  219. _configService = configService;
  220. _robotService = robotService;
  221. _scannerService = scannerService;
  222. _cameraService = cameraService;
  223. _feederService = feederService;
  224. _plcService = plcService;
  225. _calibrationService = calibrationService;
  226. yieldtimer = new Timer(DoYieldTime, null, 10000, 1000);
  227. Renders = new ObservableCollection<ShowRender>();
  228. _configService = configService;
  229. _productService = productService;
  230. _remoteCommandService = remoteCommandService;
  231. _systemDatabaseService = systemDatabaseService;
  232. _lightManagerService = lightManagerService;
  233. _mesService = mesService;
  234. }
  235. #region 初始化硬件模块
  236. /// <summary>
  237. /// 初始化Feeder
  238. /// </summary>
  239. /// <returns></returns>
  240. public async Task<(bool IsSucceed, string Msg)> InitFeeders()
  241. {
  242. var feeders = _configService.GetAllFeeders();
  243. StringBuilder sb = new StringBuilder();
  244. foreach (var item in feeders)
  245. {
  246. _feederService.CreateFeeder(item.Id, item.FeederNo, item.FeederName, item.IP, item.Port, item.FeederBrand);
  247. var feeder = _feederService.GetFeeder(item.Id);
  248. Status.Add(new StatusInfo(item.Id, item.FeederName + $"{Lang.未连接}", new SolidColorBrush(Colors.Red)));
  249. try
  250. {
  251. feeder.FeederConnectionStatusChanged += Management_FeederConnectionStatusChanged;
  252. await feeder.ConnectAsync(); //连接Feeder
  253. //SendTaskMessage($"{item.FeederName}已连接!", MessageLevel.Debug);
  254. }
  255. catch (Exception ex)
  256. {
  257. sb.AppendLine($"{item.FeederName}:{Lang.断开连接}![{ex.Message}]");
  258. SendTaskMessage($"{item.FeederName}{Lang.断开连接}!", MessageLevel.Alarm);
  259. }
  260. }
  261. if (sb.Length == 0)
  262. {
  263. return (true, "");
  264. }
  265. else
  266. {
  267. return (false, sb.ToString());
  268. }
  269. }
  270. /// <summary>
  271. /// 初始化机器人
  272. /// </summary>
  273. /// <returns></returns>
  274. public async Task<(bool IsSucceed, string Msg)> InitRobots()
  275. {
  276. var robots = _configService.GetAllRobots();
  277. StringBuilder sb = new StringBuilder();
  278. foreach (var item in robots)
  279. {
  280. _robotService.CreateRobot(item.Id, item);
  281. try
  282. {
  283. Status.Add(new StatusInfo(item.Id, item.RobotName + $"{Lang.未连接}", new SolidColorBrush(Colors.Red)));
  284. var robot = _robotService.GetRobot(item.Id);
  285. robot.ReceivedEvent += Management_ReceivedEvent;
  286. robot.SendEvent += Management_SendEvent;
  287. robot.ConnectedEvent += Management_ConnectedEvent;
  288. robot.DisconnectedEvent += Management_DisconnectedEvent;
  289. await robot.ConnectAsync(); //连接Robot
  290. SendTaskMessage($"{item.RobotName}{Lang.已连接}!", MessageLevel.Debug);
  291. }
  292. catch (Exception ex)
  293. {
  294. sb.AppendLine($"{item.RobotName}:{Lang.断开连接}![{ex.Message}]");
  295. SendTaskMessage($"{item.RobotName}{Lang.断开连接}!", MessageLevel.Alarm);
  296. }
  297. }
  298. if (sb.Length == 0)
  299. {
  300. return (true, "");
  301. }
  302. else
  303. {
  304. return (false, sb.ToString());
  305. }
  306. }
  307. /// <summary>
  308. /// 初始化扫码枪
  309. /// </summary>
  310. /// <returns></returns>
  311. public async Task<(bool IsSucceed, string Msg)> InitScanners()
  312. {
  313. var scanners = _configService.GetAllScanners();
  314. StringBuilder sb = new StringBuilder();
  315. foreach (var item in scanners)
  316. {
  317. _scannerService.CreateScanner(item.Id, item);
  318. try
  319. {
  320. Status.Add(new StatusInfo(item.Id, item.ScannerName + $"{Lang.未连接}", new SolidColorBrush(Colors.Red)));
  321. var scanner = _scannerService.GetScanner(item.Id);
  322. scanner.ReceivedEvent += Management_ScannerReceivedEvent;
  323. scanner.SendEvent += Management_ScannerSendEvent;
  324. scanner.ConnectedEvent += Management_ScannerConnectedEvent;
  325. scanner.DisconnectedEvent += Management_ScannerDisconnectedEvent;
  326. await scanner.ConnectAsync(); //连接Scanner
  327. SendTaskMessage($"{item.ScannerName}{Lang.已连接}!", MessageLevel.Debug);
  328. }
  329. catch (Exception ex)
  330. {
  331. sb.AppendLine($"{item.ScannerName}:{Lang.断开连接}![{ex.Message}]");
  332. SendTaskMessage($"{item.ScannerName}{Lang.断开连接}!", MessageLevel.Alarm);
  333. }
  334. }
  335. if (sb.Length == 0)
  336. {
  337. return (true, "");
  338. }
  339. else
  340. {
  341. return (false, sb.ToString());
  342. }
  343. }
  344. /// <summary>
  345. /// 初始化PLC
  346. /// </summary>
  347. /// <returns></returns>
  348. public async Task<(bool IsSucceed, string Msg)> InitPlc()
  349. {
  350. var plcs = _configService.GetAllPlcs();
  351. StringBuilder sb = new StringBuilder();
  352. foreach (var item in plcs)
  353. {
  354. try
  355. {
  356. _plcService.CreatePlc(item.Id, item);
  357. var plc = _plcService.GetPlc(item.Id);
  358. Status.Add(new StatusInfo(item.Id, item.Name + $"{Lang.未连接}", new SolidColorBrush(Colors.Red)));
  359. plc.ConnectChangedEvent += Management_PlcConnectChangedEvent;
  360. await plc.ConnectAsync(); //连接PLC
  361. //SendTaskMessage($"{item.Name}{Lang.已连接}!", MessageLevel.Debug);
  362. }
  363. catch (Exception ex)
  364. {
  365. sb.AppendLine($"{item.Name}:{Lang.断开连接}![{ex.Message}]");
  366. SendTaskMessage($"{item.Name}{Lang.断开连接}!", MessageLevel.Alarm);
  367. }
  368. }
  369. try
  370. {
  371. await WriteSystemParameterToPlcAsync(_configService.GetSystemConfiguration());
  372. RegisterPlcMonitorAddress();
  373. }
  374. catch (Exception ex)
  375. {
  376. LogHelper.WriteLogError("为PLC写入系统参数和订阅变量时出错", ex);
  377. }
  378. if (sb.Length == 0)
  379. {
  380. return (true, "");
  381. }
  382. else
  383. {
  384. return (false, sb.ToString());
  385. }
  386. }
  387. /// <summary>
  388. /// 初始化相机
  389. /// </summary>
  390. /// <returns></returns>
  391. public async Task<(bool IsSucceed, string Msg)> InitCameras()
  392. {
  393. var cameras = _configService.GetAllCameras();
  394. StringBuilder sb = new StringBuilder();
  395. foreach (var item in cameras)
  396. {
  397. if (item.DisplatConfigs != null)
  398. {
  399. foreach (var item1 in item.DisplatConfigs)
  400. {
  401. Renders.Add(new ShowRender() { Id = item1.Id, DisplayName = item1.DisplayName });
  402. }
  403. }
  404. _cameraService.CreateCamera(item.Id, item);
  405. try
  406. {
  407. var camera = _cameraService.GetCamera(item.Id);
  408. Status.Add(new StatusInfo(item.Id, item.CameraName + $"{Lang.未连接}", new SolidColorBrush(Colors.Red)));
  409. camera.CameraConnectChangedEvent += Management_CameraConnectChangedEvent;
  410. camera.ImageCallbackEvent += Camera_ImageCallbackEvent;
  411. try
  412. {
  413. if (await camera.OpenDeviceAsync())
  414. {
  415. SendTaskMessage($"{item.CameraName}{Lang.已连接}!", MessageLevel.Debug);
  416. }
  417. else
  418. {
  419. SendTaskMessage($"{item.CameraName}{Lang.连接失败}!", MessageLevel.Alarm);
  420. sb.AppendLine($"{item.CameraName}:{Lang.连接失败}!");
  421. }
  422. }
  423. catch (Exception ex)
  424. {
  425. SendTaskMessage($"{item.CameraName}{ex.Message}!", MessageLevel.Alarm);
  426. sb.AppendLine($"{item.CameraName}:{ex.Message}!");
  427. }
  428. }
  429. catch (Exception ex)
  430. {
  431. SendTaskMessage($"{item.CameraName}{Lang.连接失败}!", MessageLevel.Alarm);
  432. sb.AppendLine($"{item.CameraName}:{Lang.连接失败}!:{ex.Message}");
  433. }
  434. }
  435. _container.Resolve<ShowVisionRenderViewModel>().Renders = Renders;
  436. if (sb.Length == 0)
  437. {
  438. return (true, "");
  439. }
  440. else
  441. {
  442. return (false, sb.ToString());
  443. }
  444. }
  445. private void Camera_ImageCallbackEvent(ICogImage arg1, TimeSpan arg2, string arg3, Guid cameraId)
  446. {
  447. var camera = _configService.GetCamera(cameraId);
  448. SendTaskMessage($"相机[{camera.CameraName}]图像接收完成!", MessageLevel.Info);
  449. //if (camera.CameraNo == 1)
  450. //{
  451. // ImageData[1] = 1;
  452. //}
  453. //else if (camera.CameraNo == 2)
  454. //{
  455. // ImageData[2] = 1;
  456. //}
  457. //else if (camera.CameraNo == 3)
  458. //{
  459. // ImageData[3] = 1;
  460. // ImageData[4] = 1;
  461. //}
  462. //_eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
  463. //{
  464. // CameraName = camera.CameraName,
  465. // Id = cameraId,
  466. // Image = arg1,
  467. // Graphic = null,
  468. // Record = null,
  469. // Result = false,
  470. // IsShow = true,
  471. //});
  472. // 通知等待方:该相机新图到达
  473. //SignalImageArrived(cameraId, arg1);
  474. }
  475. /// <summary>
  476. /// 初始化光源控制器
  477. /// </summary>
  478. /// <returns></returns>
  479. public async Task<(bool IsSucceed, string Msg)> InitLightControllers()
  480. {
  481. var lightcontrollers = _configService.GetAllLightControllers();
  482. StringBuilder sb = new StringBuilder();
  483. foreach (var item in lightcontrollers)
  484. {
  485. try
  486. {
  487. var lishtCtr = await _lightManagerService.RegisterControllerAsync(item.Id, item);
  488. //var lightcontroller = _cameraService.GetLightController(item.Id);
  489. //await lightcontroller.ConnectAsync(); //连接光源控制器
  490. //SendTaskMessage($"{item.LightControllerName}{Lang.已连接}!", MessageLevel.Debug);
  491. }
  492. catch (Exception ex)
  493. {
  494. //sb.AppendLine($"{item.LightControllerName}:{Lang.断开连接}![{ex.Message}]");
  495. //SendTaskMessage($"{item.LightControllerName}{Lang.断开连接}!", MessageLevel.Alarm);
  496. }
  497. }
  498. if (lightcontrollers.Count > 0)
  499. {
  500. var result = await _lightManagerService.ConnectAllAsync();
  501. if (result)
  502. {
  503. return (true, "");
  504. }
  505. else
  506. {
  507. return (false, "Light Controller Connect Failed!");
  508. }
  509. }
  510. return (true, "");
  511. //if (sb.Length == 0)
  512. //{
  513. // return (true, "");
  514. //}
  515. //else
  516. //{
  517. // return (false, sb.ToString());
  518. //}
  519. }
  520. /// <summary>
  521. /// 初始化后台TCP服务器通讯
  522. /// </summary>
  523. public void InitBgTcp()
  524. {
  525. var config = _configService.GetBgTcp();
  526. try
  527. {
  528. BgCommunicate = new BgCommunicate(config);
  529. BgCommunicate.ConnectedEvent += BgCommunicate_ConnectedEvent;
  530. BgCommunicate.DisconnectedEvent += BgCommunicate_DisconnectedEvent;
  531. BgCommunicate.ReceivedEvent += BgCommunicate_ReceivedEvent;
  532. BgCommunicate.SendEvent += BgCommunicate_SendEvent;
  533. BgCommunicate.StartListening();
  534. SendTaskMessage($"{Lang.已开启监听端口}:{config.Port}", MessageLevel.Debug);
  535. }
  536. catch (Exception ex)
  537. {
  538. SendTaskMessage($"{Lang.未开启监听端口}:{config.Port}", MessageLevel.Error);
  539. LogHelper.WriteLogError("开启后台服务器通讯时出错!", ex);
  540. }
  541. }
  542. /// <summary>
  543. /// 初始化后台ModbusTCP从站
  544. /// </summary>
  545. public void InitModbusTcp()
  546. {
  547. try
  548. {
  549. var config = _configService.GetBgModbusTcp();
  550. BgModbusTcpCommunicate = new BgModbusTcpCommunicate(config);
  551. if (config.IsEnabled)
  552. {
  553. BgModbusTcpCommunicate.Listen();
  554. SendTaskMessage($"Start Modbus Tcp Slave:{BgModbusTcpCommunicate.IP}:{BgModbusTcpCommunicate.Port}:{BgModbusTcpCommunicate.SlaveID}", MessageLevel.Debug);
  555. }
  556. }
  557. catch (Exception ex)
  558. {
  559. SendTaskMessage($"No Start Modbus Tcp Slave:{ex.Message}", MessageLevel.Alarm);
  560. LogHelper.WriteLogError("开启后台Modbus TCP通讯时出错!", ex);
  561. }
  562. }
  563. /// <summary>
  564. /// 初始化后台脚本
  565. /// </summary>
  566. public void InitBackgroundcript()
  567. {
  568. try
  569. {
  570. if (!Directory.Exists(FilePath.BackgroundScriptPath))
  571. {
  572. Directory.CreateDirectory(FilePath.BackgroundScriptPath);
  573. }
  574. try
  575. {
  576. string[] files = Directory.GetFiles(FilePath.BackgroundScriptPath);
  577. List<string> ScriptFilesCollection = new List<string>();
  578. foreach (string file in files)
  579. {
  580. string fileName = Path.GetFileName(file);
  581. string fileExtension = Path.GetExtension(file);
  582. if (fileExtension == ".cs")
  583. {
  584. ScriptFilesCollection.Add(file);
  585. }
  586. }
  587. foreach (var item in ScriptFilesCollection)
  588. {
  589. try
  590. {
  591. string script = FileHelper.ReadFile(item);
  592. SendTaskMessage($"{Lang.执行脚本}:{item}", MessageLevel.Info);
  593. Task.Factory.StartNew(() =>
  594. {
  595. ScriptHelper.ExecuteScriptingAsync(script, _regionManager, _eventAggregator, _container, rst =>
  596. {
  597. if (!rst.Item1)
  598. {
  599. foreach (var err in rst.Item2)
  600. {
  601. SendTaskMessage($"{Lang.后台脚本出错}:{err}", MessageLevel.Error);
  602. }
  603. }
  604. });
  605. });
  606. }
  607. catch (Exception ex)
  608. {
  609. LogHelper.WriteLogError($"开启脚本时出错:{item}", ex);
  610. }
  611. }
  612. }
  613. catch (Exception ex)
  614. {
  615. LogHelper.WriteLogError("读取本地脚本文件列表时出错", ex);
  616. }
  617. }
  618. catch (Exception ex)
  619. {
  620. LogHelper.WriteLogError("开启后台脚本时出错!", ex);
  621. }
  622. }
  623. /// <summary>
  624. /// 初始化电批
  625. /// </summary>
  626. /// <returns></returns>
  627. public async Task InitScrewDriver()
  628. {
  629. try
  630. {
  631. var screwDriverConfig = _configService.GetScrewDriverConfig();
  632. ScrewDriver = new XYD_ScrewDriver(screwDriverConfig.IPAdress, screwDriverConfig.Port);
  633. Status.Add(new StatusInfo(ScrewDriver.Id, "电批未连接", new SolidColorBrush(Colors.Red)));
  634. ScrewDriver.ConnectStateChangedEvent += ScrewDriver_ConnectStateChangedEvent;
  635. ScrewDriver.SendTimeout = screwDriverConfig.SendTimeout;
  636. screwDriverConfig.ReceiveTimeout = screwDriverConfig.ReceiveTimeout;
  637. var isConnected = await ScrewDriver.ConnectAsync();
  638. if (isConnected)
  639. {
  640. SendTaskMessage($"电批已连接", MessageLevel.Debug);
  641. }
  642. else
  643. {
  644. SendTaskMessage($"电批连接失败", MessageLevel.Error);
  645. }
  646. }
  647. catch (Exception ex)
  648. {
  649. SendTaskMessage($"电批连接失败:{ex.Message}", MessageLevel.Alarm);
  650. LogHelper.WriteLogError("连接电批时出错!", ex);
  651. }
  652. }
  653. #endregion
  654. #region 机器人指令执行
  655. public Dictionary<Guid, CancellationTokenSource> RobotTCPCollection = new Dictionary<Guid, CancellationTokenSource>();
  656. public Dictionary<Guid, CancellationTokenSource> ScannerTCPCollection = new Dictionary<Guid, CancellationTokenSource>();
  657. /// <summary>
  658. /// 机器人TCP接收
  659. /// </summary>
  660. /// <param name="arg1"></param>
  661. /// <param name="arg2"></param>
  662. /// <param name="arg3"></param>
  663. private async void Management_ReceivedEvent(Guid robotid, object arg2, TouchSocket.Sockets.ReceivedDataEventArgs e)
  664. {
  665. try
  666. {
  667. if (!RobotTCPCollection.ContainsKey(robotid))
  668. RobotTCPCollection.Add(robotid, new CancellationTokenSource());
  669. else
  670. {
  671. if (RobotTCPCollection[robotid].IsCancellationRequested)
  672. {
  673. RobotTCPCollection[robotid] = new CancellationTokenSource();
  674. }
  675. }
  676. var robot = await _robotService.GetRobotAsync(robotid);
  677. //从服务器收到信息。但是一般byteBlock和requestInfo会根据适配器呈现不同的值。
  678. var buffer = e.ByteBlock.Span.ToString(robot.GetEncoding());
  679. SendTaskMessage($"{robot.Name}Received:{buffer}", MessageLevel.Info);
  680. var _ = _remoteCommandService.ExecuteAsync(buffer, RobotTCPCollection[robotid].Token, async msg =>
  681. {
  682. try
  683. {
  684. if (robot.ConnectType == TCPConnectType.Client)
  685. {
  686. if (robot.IsConnected)
  687. {
  688. await robot.SendAsync($"{msg}");
  689. }
  690. }
  691. else
  692. {
  693. var cient = (ITcpSessionClient)arg2;
  694. if (cient.Online)
  695. {
  696. await robot.SendAsync(cient, $"{msg}");
  697. }
  698. }
  699. }
  700. catch (Exception ex)
  701. {
  702. LogHelper.WriteLogError("TCP发送数据时出错!", ex);
  703. SendTaskMessage(ex.Message, MessageLevel.Alarm);
  704. }
  705. });
  706. }
  707. catch (Exception ex)
  708. {
  709. LogHelper.WriteLogError("处理机器人接收的命令时出错!", ex);
  710. SendTaskMessage(ex.Message, MessageLevel.Alarm);
  711. }
  712. }
  713. /// <summary>
  714. /// 扫码枪TCP接收
  715. /// </summary>
  716. /// <param name="arg1"></param>
  717. /// <param name="arg2"></param>
  718. /// <param name="arg3"></param>
  719. private async void Management_ScannerReceivedEvent(Guid scannerid, object arg2, TouchSocket.Sockets.ReceivedDataEventArgs e)
  720. {
  721. try
  722. {
  723. if (!ScannerTCPCollection.ContainsKey(scannerid))
  724. ScannerTCPCollection.Add(scannerid, new CancellationTokenSource());
  725. else
  726. {
  727. if (ScannerTCPCollection[scannerid].IsCancellationRequested)
  728. {
  729. ScannerTCPCollection[scannerid] = new CancellationTokenSource();
  730. }
  731. }
  732. var scanner = await _scannerService.GetScannerAsync(scannerid);
  733. //从服务器收到信息。但是一般byteBlock和requestInfo会根据适配器呈现不同的值。
  734. var buffer = e.ByteBlock.Span.ToString(scanner.GetEncoding());
  735. SendTaskMessage($"{scanner.Name}Received:{buffer}", MessageLevel.Info);
  736. var _ = _remoteCommandService.ExecuteAsync(buffer, ScannerTCPCollection[scannerid].Token, async msg =>
  737. {
  738. try
  739. {
  740. if (scanner.ConnectType == TCPConnectType.Client)
  741. {
  742. if (scanner.IsConnected)
  743. {
  744. await scanner.SendAsync($"{msg}");
  745. }
  746. }
  747. else
  748. {
  749. var cient = (ITcpSessionClient)arg2;
  750. if (cient.Online)
  751. {
  752. await scanner.SendAsync(cient, $"{msg}");
  753. }
  754. }
  755. }
  756. catch (Exception ex)
  757. {
  758. LogHelper.WriteLogError("TCP发送数据时出错!", ex);
  759. SendTaskMessage(ex.Message, MessageLevel.Alarm);
  760. }
  761. });
  762. }
  763. catch (Exception ex)
  764. {
  765. LogHelper.WriteLogError("处理机器人接收的命令时出错!", ex);
  766. SendTaskMessage(ex.Message, MessageLevel.Alarm);
  767. }
  768. }
  769. #endregion
  770. #region 机器人&Feeder&相机连接状态事件
  771. /// <summary>
  772. /// 机器人发送事件
  773. /// </summary>
  774. /// <param name="arg1"></param>
  775. /// <param name="arg2"></param>
  776. /// <param name="arg3"></param>
  777. /// <exception cref="NotImplementedException"></exception>
  778. private void Management_SendEvent(Guid robotid, object arg2, string arg3)
  779. {
  780. var r = _robotService.GetRobot(robotid);
  781. SendTaskMessage($"{r.Name}Send:{arg3}", MessageLevel.Info);
  782. }
  783. /// <summary>
  784. /// 扫码枪发送事件
  785. /// </summary>
  786. /// <param name="arg1"></param>
  787. /// <param name="arg2"></param>
  788. /// <param name="arg3"></param>
  789. /// <exception cref="NotImplementedException"></exception>
  790. private void Management_ScannerSendEvent(Guid scannerid, object arg2, string arg3)
  791. {
  792. var r = _scannerService.GetScanner(scannerid);
  793. SendTaskMessage($"{r.Name}Send:{arg3}", MessageLevel.Info);
  794. }
  795. /// <summary>
  796. /// 机器人断开连接时
  797. /// </summary>
  798. /// <param name="arg1"></param>
  799. /// <param name="arg2"></param>
  800. /// <param name="arg3"></param>
  801. /// <exception cref="NotImplementedException"></exception>
  802. private void Management_DisconnectedEvent(Guid robotid, object arg2, ClosedEventArgs arg3)
  803. {
  804. if (RobotTCPCollection.ContainsKey(robotid))
  805. {
  806. RobotTCPCollection[robotid].Cancel();
  807. }
  808. var r = _configService.GetRobot(robotid);
  809. if (r.ConnectType == TCPConnectType.Server)
  810. {
  811. ITcpSessionClient socketClient = arg2 as ITcpSessionClient;
  812. SendTaskMessage($"{r.RobotName}[{socketClient.Id}:{socketClient.IP}]{Lang.断开连接}!", MessageLevel.Error);
  813. var robot = _robotService.GetRobot(robotid);
  814. if (robot.TcpService.Count < 1)
  815. {
  816. var sta = Status.FirstOrDefault(s => s.ID == robotid);
  817. App.Current.Dispatcher.Invoke(new
  818. Action(() =>
  819. {
  820. sta.Message = $"{r.RobotName}{Lang.未连接}";
  821. sta.Background = new SolidColorBrush(Colors.Red);
  822. }));
  823. }
  824. }
  825. else
  826. {
  827. SendTaskMessage($"{r.RobotName}{Lang.断开连接}!", MessageLevel.Error);
  828. var sta = Status.FirstOrDefault(s => s.ID == robotid);
  829. App.Current.Dispatcher.Invoke(new
  830. Action(() =>
  831. {
  832. sta.Message = $"{r.RobotName}{Lang.断开连接}";
  833. sta.Background = new SolidColorBrush(Colors.Red);
  834. }));
  835. }
  836. }
  837. /// <summary>
  838. /// 扫码枪断开连接时
  839. /// </summary>
  840. /// <param name="arg1"></param>
  841. /// <param name="arg2"></param>
  842. /// <param name="arg3"></param>
  843. /// <exception cref="NotImplementedException"></exception>
  844. private void Management_ScannerDisconnectedEvent(Guid scannerid, object arg2, ClosedEventArgs arg3)
  845. {
  846. if (ScannerTCPCollection.ContainsKey(scannerid))
  847. {
  848. ScannerTCPCollection[scannerid].Cancel();
  849. }
  850. var r = _configService.GetScanner(scannerid);
  851. if (r.ConnectType == TCPConnectType.Server)
  852. {
  853. ITcpSessionClient socketClient = arg2 as ITcpSessionClient;
  854. SendTaskMessage($"{r.ScannerName}[{socketClient.Id}:{socketClient.IP}]{Lang.断开连接}!", MessageLevel.Error);
  855. var scanner = _scannerService.GetScanner(scannerid);
  856. if (scanner.TcpService.Count < 1)
  857. {
  858. var sta = Status.FirstOrDefault(s => s.ID == scannerid);
  859. App.Current.Dispatcher.Invoke(new
  860. Action(() =>
  861. {
  862. sta.Message = $"{r.ScannerName}{Lang.未连接}";
  863. sta.Background = new SolidColorBrush(Colors.Red);
  864. }));
  865. }
  866. }
  867. else
  868. {
  869. SendTaskMessage($"{r.ScannerName}{Lang.断开连接}!", MessageLevel.Error);
  870. var sta = Status.FirstOrDefault(s => s.ID == scannerid);
  871. App.Current.Dispatcher.Invoke(new
  872. Action(() =>
  873. {
  874. sta.Message = $"{r.ScannerName}{Lang.断开连接}";
  875. sta.Background = new SolidColorBrush(Colors.Red);
  876. }));
  877. }
  878. }
  879. /// <summary>
  880. /// 机器人连接成功时
  881. /// </summary>
  882. /// <param name="arg1"></param>
  883. /// <param name="arg2"></param>
  884. /// <param name="arg3"></param>
  885. /// <exception cref="NotImplementedException"></exception>
  886. private void Management_ConnectedEvent(Guid robotid, object arg2, ConnectedEventArgs arg3)
  887. {
  888. var r = _configService.GetRobot(robotid);
  889. if (r.ConnectType == TCPConnectType.Server)
  890. {
  891. ITcpSessionClient socketClient = arg2 as ITcpSessionClient;
  892. SendTaskMessage($"{r.RobotName}[{socketClient.Id}:{socketClient.IP}]{Lang.已连接}!", MessageLevel.Debug);
  893. var robot = _robotService.GetRobot(robotid);
  894. if (robot.TcpService.Count > 0)
  895. {
  896. var sta = Status.FirstOrDefault(s => s.ID == robotid);
  897. App.Current.Dispatcher.Invoke(new
  898. Action(() =>
  899. {
  900. sta.Message = $"{r.RobotName}{Lang.已连接}";
  901. sta.Background = new SolidColorBrush(Colors.Green);
  902. }));
  903. }
  904. }
  905. else
  906. {
  907. SendTaskMessage($"{r.RobotName}{Lang.已连接}!", MessageLevel.Debug);
  908. var sta = Status.FirstOrDefault(s => s.ID == robotid);
  909. App.Current.Dispatcher.Invoke(new
  910. Action(() =>
  911. {
  912. sta.Message = $"{r.RobotName}{Lang.已连接}";
  913. sta.Background = new SolidColorBrush(Colors.Green);
  914. }));
  915. }
  916. }
  917. /// <summary>
  918. /// 扫码枪连接成功时
  919. /// </summary>
  920. /// <param name="arg1"></param>
  921. /// <param name="arg2"></param>
  922. /// <param name="arg3"></param>
  923. /// <exception cref="NotImplementedException"></exception>
  924. private void Management_ScannerConnectedEvent(Guid scannerid, object arg2, ConnectedEventArgs arg3)
  925. {
  926. var r = _configService.GetScanner(scannerid);
  927. if (r.ConnectType == TCPConnectType.Server)
  928. {
  929. ITcpSessionClient socketClient = arg2 as ITcpSessionClient;
  930. SendTaskMessage($"{r.ScannerName}[{socketClient.Id}:{socketClient.IP}]{Lang.已连接}!", MessageLevel.Debug);
  931. var scanner = _scannerService.GetScanner(scannerid);
  932. if (scanner.TcpService.Count > 0)
  933. {
  934. var sta = Status.FirstOrDefault(s => s.ID == scannerid);
  935. App.Current.Dispatcher.Invoke(new
  936. Action(() =>
  937. {
  938. sta.Message = $"{r.ScannerName}{Lang.已连接}";
  939. sta.Background = new SolidColorBrush(Colors.Green);
  940. }));
  941. }
  942. }
  943. else
  944. {
  945. SendTaskMessage($"{r.ScannerName}{Lang.已连接}!", MessageLevel.Debug);
  946. var sta = Status.FirstOrDefault(s => s.ID == scannerid);
  947. App.Current.Dispatcher.Invoke(new
  948. Action(() =>
  949. {
  950. sta.Message = $"{r.ScannerName}{Lang.已连接}";
  951. sta.Background = new SolidColorBrush(Colors.Green);
  952. }));
  953. }
  954. }
  955. /// <summary>
  956. /// Feeder连接状态改变时
  957. /// </summary>
  958. /// <param name="sender"></param>
  959. /// <param name="state"></param>
  960. private void Management_FeederConnectionStatusChanged(object sender, bool state)
  961. {
  962. IFeeder feeder = sender as IFeeder;
  963. var sta = Status.FirstOrDefault(s => s.ID == feeder.Id);
  964. if (state)
  965. {
  966. App.Current.Dispatcher.Invoke(new
  967. Action(() =>
  968. {
  969. sta.Message = $"{feeder.Name}{Lang.已连接}";
  970. sta.Background = new SolidColorBrush(Colors.Green);
  971. }));
  972. SendTaskMessage($"{feeder.Name}{Lang.已连接}!", MessageLevel.Debug);
  973. }
  974. else
  975. {
  976. App.Current.Dispatcher.Invoke(new
  977. Action(() =>
  978. {
  979. sta.Message = $"{feeder.Name}{Lang.未连接}";
  980. sta.Background = new SolidColorBrush(Colors.Red);
  981. }));
  982. SendTaskMessage($"{feeder.Name}{Lang.断开连接}!", MessageLevel.Error);
  983. }
  984. }
  985. /// <summary>
  986. /// 相机连接或者断开时
  987. /// </summary>
  988. /// <param name="id"></param>
  989. /// <param name="state"></param>
  990. private void Management_CameraConnectChangedEvent(Guid id, bool state)
  991. {
  992. var sta = Status.FirstOrDefault(s => s.ID == id);
  993. var camera = _configService.GetCamera(id);
  994. if (sta != null && camera != null)
  995. {
  996. if (state)
  997. {
  998. App.Current.Dispatcher.Invoke(new Action(() =>
  999. {
  1000. sta.Message = $"{camera.CameraName}{Lang.已连接}";
  1001. sta.Background = new SolidColorBrush(Colors.Green);
  1002. }));
  1003. }
  1004. else
  1005. {
  1006. App.Current.Dispatcher.Invoke(new Action(() =>
  1007. {
  1008. sta.Message = $"{camera.CameraName}{Lang.断开连接}";
  1009. sta.Background = new SolidColorBrush(Colors.Red);
  1010. }));
  1011. }
  1012. }
  1013. }
  1014. /// <summary>
  1015. /// PLC连接状态改变事件
  1016. /// </summary>
  1017. /// <param name="plc"></param>
  1018. /// <param name="isconnected"></param>
  1019. private void Management_PlcConnectChangedEvent(object sender, bool isconnected)
  1020. {
  1021. IPlc plc = sender as IPlc;
  1022. var sta = Status.FirstOrDefault(s => s.ID == plc.Id);
  1023. if (plc.IsConnected)
  1024. {
  1025. SendTaskMessage($"{plc.Name}{Lang.已连接}!", MessageLevel.Debug);
  1026. if (sta == null) return;
  1027. App.Current.Dispatcher.Invoke(new
  1028. Action(() =>
  1029. {
  1030. sta.Message = $"{plc.Name}{Lang.已连接}";
  1031. sta.Background = new SolidColorBrush(Colors.Green);
  1032. }));
  1033. }
  1034. else
  1035. {
  1036. SendTaskMessage($"{plc.Name}{Lang.断开连接}!", MessageLevel.Error);
  1037. if (sta == null) return;
  1038. App.Current.Dispatcher.Invoke(new
  1039. Action(() =>
  1040. {
  1041. sta.Message = $"{plc.Name}{Lang.未连接}";
  1042. sta.Background = new SolidColorBrush(Colors.Red);
  1043. }));
  1044. }
  1045. }
  1046. /// <summary>
  1047. /// 电批连接状态改变时
  1048. /// </summary>
  1049. /// <param name="screwDevice"></param>
  1050. /// <param name="state"></param>
  1051. private void ScrewDriver_ConnectStateChangedEvent(object screwDevice, bool state)
  1052. {
  1053. try
  1054. {
  1055. XYD_ScrewDriver screwDriver = screwDevice as XYD_ScrewDriver;
  1056. if (state)
  1057. {
  1058. SendTaskMessage($"电批{Lang.已连接}!", MessageLevel.Debug);
  1059. var sta = Status.FirstOrDefault(s => s.ID == screwDriver.Id);
  1060. App.Current.Dispatcher.Invoke(new
  1061. Action(() =>
  1062. {
  1063. sta.Message = $"电批{Lang.已连接}";
  1064. sta.Background = new SolidColorBrush(Colors.Green);
  1065. }));
  1066. }
  1067. else
  1068. {
  1069. SendTaskMessage($"电批{Lang.未连接}!", MessageLevel.Error);
  1070. var sta = Status.FirstOrDefault(s => s.ID == screwDriver.Id);
  1071. App.Current.Dispatcher.Invoke(new
  1072. Action(() =>
  1073. {
  1074. sta.Message = $"电批{Lang.未连接}";
  1075. sta.Background = new SolidColorBrush(Colors.Red);
  1076. }));
  1077. }
  1078. }
  1079. catch (Exception ex)
  1080. {
  1081. LogHelper.WriteLogError("电批连接状态改变时出错了", ex);
  1082. }
  1083. }
  1084. #endregion
  1085. #region 后台服务器通讯事件
  1086. private void BgCommunicate_SendEvent(ITcpSessionClient client, string msg)
  1087. {
  1088. SendTaskMessage($"{Lang.服务器}[{client.ServicePort}] Send To {Lang.客户端}[{client.Id}:{client.IP}]:{msg}", MessageLevel.Info);
  1089. }
  1090. public Dictionary<string, CancellationTokenSource> BgCommunicateollection = new Dictionary<string, CancellationTokenSource>();
  1091. private async void BgCommunicate_ReceivedEvent(ITcpSessionClient client, string msg)
  1092. {
  1093. try
  1094. {
  1095. if (!BgCommunicateollection.ContainsKey(client.Id))
  1096. {
  1097. BgCommunicateollection.Add(client.Id, new CancellationTokenSource());
  1098. }
  1099. SendTaskMessage($"{Lang.服务器}[{client.ServicePort}]ReceiveFor{Lang.客户端}[{client.Id}:{client.IP}]:{msg}", MessageLevel.Info);
  1100. var _ = _remoteCommandService.ExecuteAsync(msg, BgCommunicateollection[client.Id].Token, async response =>
  1101. {
  1102. try
  1103. {
  1104. if (!client.Online)
  1105. {
  1106. return;
  1107. }
  1108. await BgCommunicate.SendAsync(client, $"{response}");
  1109. }
  1110. catch (Exception ex)
  1111. {
  1112. LogHelper.WriteLogError("后台TCP发送数据时出错!", ex);
  1113. SendTaskMessage(ex.Message, MessageLevel.Alarm);
  1114. }
  1115. });
  1116. }
  1117. catch (Exception ex)
  1118. {
  1119. LogHelper.WriteLogError("处理后台服务器接收的命令时出错!", ex);
  1120. SendTaskMessage(ex.Message, MessageLevel.Alarm);
  1121. }
  1122. }
  1123. private void BgCommunicate_DisconnectedEvent(ITcpSessionClient client, ClosedEventArgs e)
  1124. {
  1125. SendTaskMessage($"{Lang.服务器}[{client.ServicePort}]{Lang.客户端}[{client.Id}:{client.IP}]{Lang.断开连接}!", MessageLevel.Alarm);
  1126. if (BgCommunicateollection.ContainsKey(client.Id))
  1127. {
  1128. BgCommunicateollection[client.Id].Cancel();
  1129. }
  1130. }
  1131. private void BgCommunicate_ConnectedEvent(ITcpSessionClient client, ConnectedEventArgs e)
  1132. {
  1133. SendTaskMessage($"{Lang.服务器}[{client.ServicePort}]{Lang.客户端}[{client.Id}:{client.IP}]{Lang.连接成功}!", MessageLevel.Debug);
  1134. }
  1135. #endregion
  1136. #region PLC
  1137. /// <summary>
  1138. /// 将系统参数写入PLC
  1139. /// </summary>
  1140. /// <param name="systemConfiguration"></param>
  1141. /// <returns></returns>
  1142. public async Task WriteSystemParameterToPlcAsync(SystemConfiguration systemConfiguration)
  1143. {
  1144. var addressConfig = _configService.GetPlcAddresses();
  1145. var plc = _plcService.GetPlcByNumber(addressConfig.PlcNo) as OpcUaClientPLC;
  1146. if (plc == null || !plc.IsConnected) return;
  1147. Dictionary<string, object> nodeValues = new Dictionary<string, object>();
  1148. nodeValues.Add(addressConfig.Out_WorkMode.Address, (Int16)systemConfiguration.WorkMode);
  1149. nodeValues.Add(addressConfig.Out_PickPointNum.Address, (Int16)systemConfiguration.PickPointNum);
  1150. nodeValues.Add(addressConfig.Out_DowmCameraNum.Address, (Int16)systemConfiguration.DowmCameraNum);
  1151. nodeValues.Add(addressConfig.Out_UpCameraPickNum.Address, (Int16)systemConfiguration.UpCameraPickNum);
  1152. nodeValues.Add(addressConfig.Out_UpCameraPutNum.Address, (Int16)systemConfiguration.UpCameraPutNum);
  1153. nodeValues.Add(addressConfig.Out_UPCameracheckNum.Address, (Int16)systemConfiguration.UPCameracheckNum);
  1154. nodeValues.Add(addressConfig.Out_FixedCameraPickNum.Address, (Int16)systemConfiguration.FixedCameraPickNum);
  1155. nodeValues.Add(addressConfig.Out_FixedCameraPutNum.Address, (Int16)systemConfiguration.FixedCameraPutNum);
  1156. nodeValues.Add(addressConfig.Out_FixedCameracheckNum.Address, (Int16)systemConfiguration.FixedCameracheckNum);
  1157. var res = await plc.WriteNodesAsync(nodeValues);
  1158. }
  1159. /// <summary>
  1160. /// 注册需要监控的PLC地址
  1161. /// </summary>
  1162. public void RegisterPlcMonitorAddress()
  1163. {
  1164. var addressConfig = _configService.GetPlcAddresses();
  1165. var plc = _plcService.GetPlcByNumber(addressConfig.PlcNo) as OpcUaClientPLC;
  1166. if (plc == null || !plc.IsConnected) return;
  1167. //PLC地址数组
  1168. List<string> monitorNodeIds = new List<string>()
  1169. {
  1170. addressConfig.In_DowmCameraExe.Address,
  1171. addressConfig.In_UpCameraPickExe.Address,
  1172. addressConfig.In_UpCameraPutExe.Address,
  1173. addressConfig.In_UPCameracheckExe.Address,
  1174. addressConfig.In_FixedCameraPickExe.Address,
  1175. addressConfig.In_FixedCameraPutExe.Address,
  1176. addressConfig.In_FixedCameracheckExe.Address,
  1177. addressConfig.In_WorkStart.Address,
  1178. addressConfig.In_WorkDone.Address,
  1179. addressConfig.In_MesCheck.Address,
  1180. addressConfig.In_RequestPosition.Address,
  1181. };
  1182. for (int i = 0; i < 10; i++)
  1183. {
  1184. monitorNodeIds.Add(string.Format(addressConfig.In_MesCheck.Address, i));
  1185. }
  1186. //订阅PLC地址变化
  1187. plc.SubscribeNodes("AutoSensor", monitorNodeIds, PlcCommandTrigger);
  1188. }
  1189. /// <summary>
  1190. /// 写入点位信息给PLC
  1191. /// </summary>
  1192. /// <returns></returns>
  1193. public async Task WritePositionToPlcAsync()
  1194. {
  1195. var addressConfig = _configService.GetPlcAddresses();
  1196. var plc = _plcService.GetPlcByNumber(addressConfig.PlcNo) as OpcUaClientPLC;
  1197. if (plc == null || !plc.IsConnected) return;
  1198. var current = _productService.GetCurrentProduct();
  1199. if (current == null) return;
  1200. if (current.PickCameraPoints != null && current.PickCameraPoints.Count > 0)
  1201. {
  1202. foreach (var item in current.PickCameraPoints)
  1203. {
  1204. await item.WriteToPlcAddress(addressConfig.Out_PickCamera, plc);
  1205. }
  1206. }
  1207. if (current.PickPoints != null && current.PickPoints.Count > 0)
  1208. {
  1209. foreach (var item in current.PickPoints)
  1210. {
  1211. await item.WriteToPlcAddress(addressConfig.Out_Pick, plc);
  1212. }
  1213. }
  1214. if (current.SecPosCameraPoints != null && current.SecPosCameraPoints.Count > 0)
  1215. {
  1216. foreach (var item in current.SecPosCameraPoints)
  1217. {
  1218. await item.WriteToPlcAddress(addressConfig.Out_SecPosCamera, plc);
  1219. }
  1220. }
  1221. if (current.ScrewCameraPoints != null && current.ScrewCameraPoints.Count > 0)
  1222. {
  1223. foreach (var item in current.ScrewCameraPoints)
  1224. {
  1225. await item.WriteToPlcAddress(addressConfig.Out_ScrewCamera, plc);
  1226. }
  1227. }
  1228. //if (current.ScrewPoints != null && current.ScrewPoints.Count > 0)
  1229. //{
  1230. // foreach (var item in current.ScrewPoints)
  1231. // {
  1232. // await item.WriteToPlcAddress(addressConfig.Out_Screw, plc);
  1233. // }
  1234. // await plc.WriteNodeAsync(addressConfig.Out_WorkNum.Address, (Int16)current.ScrewPoints.Count);
  1235. //}
  1236. if (current.CheckCameraPoints != null && current.CheckCameraPoints.Count > 0)
  1237. {
  1238. foreach (var item in current.CheckCameraPoints)
  1239. {
  1240. await item.WriteToPlcAddress(addressConfig.Out_CheckCamera, plc);
  1241. }
  1242. }
  1243. if (current.AoiPoints != null && current.AoiPoints.Count > 0)
  1244. {
  1245. await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickNum.Address, (Int16)current.AoiPoints.Count);
  1246. foreach (var item in current.AoiPoints)
  1247. {
  1248. await item.WriteToPlcAddress(addressConfig.Out_AoiCamera, plc);
  1249. }
  1250. }
  1251. else
  1252. {
  1253. await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickNum.Address, 0);
  1254. }
  1255. }
  1256. PointF[] DowmCameraResults = new PointF[10];
  1257. PointF[] UpCameraPutResults = new PointF[10];
  1258. bool _LastDowmCameraExe = false;
  1259. bool _LastScrewTeachExe = false;
  1260. bool _LastUpCameraPickExe = false;
  1261. bool _LastUpCameraPutExe = false;
  1262. bool _LastUPCameracheckExe = false;
  1263. bool _LastFixedCameraPickExe = false;
  1264. bool _LastFixedCameraPutExe = false;
  1265. bool _LastFixedCameracheckExe = false;
  1266. Int16 _LastWorkStart = 0;
  1267. Int16 _LastWorkDone = 0;
  1268. Int16 _LastRequestPosition = 0;
  1269. Int16[] _LastMesCheck = new Int16[10];
  1270. Int16 _LastPickINC = 0;
  1271. DateTime[] _LastMesCheckTime = new DateTime[10];
  1272. List<Task<(bool IsSucceed, bool[] Result, string Message)>> _PrcTaskList = new List<Task<(bool IsSucceed, bool[] Result, string Message)>>();
  1273. private readonly object _stateLock = new object();
  1274. /// <summary>
  1275. /// PLC命令触发时
  1276. /// </summary>
  1277. /// <param name="tuple"></param>
  1278. private async void PlcCommandTrigger((string key, string nodeId, object value) tuple)
  1279. {
  1280. try
  1281. {
  1282. if (tuple.key != "AutoSensor")
  1283. {
  1284. return;
  1285. }
  1286. var addressConfig = _configService.GetPlcAddresses();
  1287. var plc = _plcService.GetPlcByNumber(addressConfig.PlcNo) as OpcUaClientPLC;
  1288. if (plc == null || !plc.IsConnected) return;
  1289. // 获取当前产品
  1290. var currentProduct = _productService.GetCurrentProduct();
  1291. if (currentProduct == null)
  1292. {
  1293. return;
  1294. }
  1295. ////获取产品编码
  1296. //_productService.CurrentProductCode = currentProduct.Name;
  1297. //string productCode = plc.ReadNode<string>(addressConfig.In_Code.Address);
  1298. ////如果产品编码为空,则以当前的时间戳作为编码
  1299. //if (string.IsNullOrEmpty(productCode))
  1300. //{
  1301. // productCode = DateTime.Now.ToString("yyyyMMddHHmmssfff");
  1302. //}
  1303. // 写入3D相机长度
  1304. if (addressConfig.In_UPCameracheckExe.Address.Contains(tuple.nodeId))
  1305. {
  1306. if (tuple.value is bool state)
  1307. {
  1308. if (_LastUPCameracheckExe != state)
  1309. {
  1310. _LastUPCameracheckExe = state;
  1311. }
  1312. else
  1313. {
  1314. return;
  1315. }
  1316. if (state)
  1317. {
  1318. SendTaskMessage($"写入3D相机长度...", MessageLevel.Debug);
  1319. //相机的编号
  1320. //Int16 cameraIndex = plc.ReadNode<Int16>(addressConfig.In_FixedCameracheckNum.Address);
  1321. // 读取相机编号
  1322. Int16 cameraIndex = plc.ReadNode<Int16>(addressConfig.In_FixedCameracheckNum.Address);
  1323. SendTaskMessage($"编号:{cameraIndex}", MessageLevel.Info);
  1324. // 找到对应编号的 PlcPoint
  1325. var targetPoint = currentProduct.AoiPoints?.FirstOrDefault(p => p.Number == cameraIndex);
  1326. if (targetPoint == null)
  1327. {
  1328. SendTaskMessage($"未找到 AOI 点位,编号:{cameraIndex}", MessageLevel.Alarm);
  1329. await plc.WriteNodeAsync(addressConfig.Out_UPCameracheckStatus.Address, (Int16)2);
  1330. return;
  1331. }
  1332. SetBatchPoints(new int[] { targetPoint.Camera_Data1, targetPoint.Camera_Data2, targetPoint.Camera_Data3, targetPoint.Camera_Data4 });
  1333. await plc.WriteNodeAsync(addressConfig.Out_UPCameracheckStatus.Address, (Int16)1);
  1334. }
  1335. else
  1336. {
  1337. SendTaskMessage($"写入3D相机长度信号已关闭", MessageLevel.Alarm);
  1338. await plc.WriteNodeAsync(addressConfig.Out_UPCameracheckStatus.Address, (Int16)0);
  1339. }
  1340. }
  1341. }
  1342. // 发送点位个数
  1343. else if (addressConfig.In_RequestPosition.Address.Contains(tuple.nodeId))
  1344. {
  1345. if (tuple.value is Int16 state)
  1346. {
  1347. if (_LastRequestPosition != state)
  1348. {
  1349. _LastRequestPosition = state;
  1350. }
  1351. else
  1352. {
  1353. return;
  1354. }
  1355. if (state == 1)
  1356. {
  1357. var current = _productService.GetCurrentProduct();
  1358. if (current == null) return;
  1359. await plc.WriteNodeAsync(addressConfig.Out_CameraDone.Address, (Int16)1);
  1360. await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickNum.Address, (Int16)current.AoiPoints.Count);
  1361. }
  1362. else
  1363. {
  1364. SendTaskMessage($"多相机坐标合并请求已结束或被取消,state={state}", MessageLevel.Alarm);
  1365. await plc.WriteNodeAsync(addressConfig.Out_CameraDone.Address, (Int16)0);
  1366. }
  1367. }
  1368. }
  1369. // 固定相机检测拍照
  1370. else if (addressConfig.In_FixedCameracheckExe.Address.Contains(tuple.nodeId))
  1371. {
  1372. if (tuple.value is bool state)
  1373. {
  1374. if (_LastFixedCameracheckExe != state)
  1375. {
  1376. _LastFixedCameracheckExe = state;
  1377. }
  1378. else
  1379. {
  1380. return;
  1381. }
  1382. if (state)
  1383. {
  1384. LockResult lockResult = new LockResult();
  1385. lockResult.TimeStart = DateTime.Now;
  1386. SendTaskMessage($"触发固定相机检测拍照...", MessageLevel.Debug);
  1387. // 读取相机编号
  1388. Int16 cameraIndex = plc.ReadNode<Int16>(addressConfig.In_FixedCameracheckNum.Address);
  1389. SendTaskMessage($"编号:{cameraIndex}", MessageLevel.Info);
  1390. // 找到对应编号的 PlcPoint
  1391. var targetPoint = currentProduct.AoiPoints?.FirstOrDefault(p => p.Number == cameraIndex);
  1392. if (targetPoint == null)
  1393. {
  1394. SendTaskMessage($"未找到 AOI 点位,编号:{cameraIndex}", MessageLevel.Alarm);
  1395. await plc.WriteNodeAsync(addressConfig.Out_FixedCameracheckStatus.Address, (Int16)2);
  1396. return;
  1397. }
  1398. // 收集要执行的流程 id(仅添加大于0的)
  1399. var procIds = new List<Guid>();
  1400. try
  1401. {
  1402. if (targetPoint.CameraProcedureId1 != Guid.Empty) procIds.Add(targetPoint.CameraProcedureId1);
  1403. }
  1404. catch { }
  1405. try
  1406. {
  1407. if (targetPoint.CameraProcedureId2 != Guid.Empty) procIds.Add(targetPoint.CameraProcedureId2);
  1408. }
  1409. catch { }
  1410. try
  1411. {
  1412. if (targetPoint.CameraProcedureId3 != Guid.Empty) procIds.Add(targetPoint.CameraProcedureId3);
  1413. }
  1414. catch { }
  1415. try
  1416. {
  1417. if (targetPoint.CameraProcedureId4 != Guid.Empty) procIds.Add(targetPoint.CameraProcedureId4);
  1418. }
  1419. catch { }
  1420. try
  1421. {
  1422. if (targetPoint.CameraProcedureId5 != Guid.Empty) procIds.Add(targetPoint.CameraProcedureId5);
  1423. }
  1424. catch { }
  1425. try
  1426. {
  1427. if (targetPoint.CameraProcedureId6 != Guid.Empty) procIds.Add(targetPoint.CameraProcedureId6);
  1428. }
  1429. catch { }
  1430. try
  1431. {
  1432. if (targetPoint.CameraProcedureId7 != Guid.Empty) procIds.Add(targetPoint.CameraProcedureId7);
  1433. }
  1434. catch { }
  1435. try
  1436. {
  1437. if (targetPoint.CameraProcedureId8 != Guid.Empty) procIds.Add(targetPoint.CameraProcedureId8);
  1438. }
  1439. catch { }
  1440. if (procIds.Count == 0)
  1441. {
  1442. SendTaskMessage($"Point#{cameraIndex} 未配置任何视觉流程 (CameraProcedureId1/2/3)", MessageLevel.Alarm);
  1443. await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)2);
  1444. return;
  1445. }
  1446. var cameraProcedures = currentProduct.CameraProcedures;
  1447. if (cameraProcedures == null || cameraProcedures.Count == 0)
  1448. {
  1449. SendTaskMessage($"当前产品未配置 CameraProcedures,无法执行视觉流程", MessageLevel.Alarm);
  1450. await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)2);
  1451. return;
  1452. }
  1453. if (cameraIndex == currentProduct.PhotoCount)
  1454. {
  1455. _PrcTaskList.Clear();
  1456. lock (_stateLock)
  1457. {
  1458. lockResultsAll.Clear();
  1459. }
  1460. App.Current.Dispatcher.Invoke(() =>
  1461. {
  1462. _eventAggregator.GetEvent<LockResetNotification>().Publish();
  1463. });
  1464. }
  1465. var sysConfig = _configService.GetSystemConfiguration();
  1466. if (sysConfig.CodeUse==true && cameraIndex == 1)
  1467. {
  1468. var cts = new CancellationTokenSource();
  1469. // CameraProcedureId 存储的是具体的视觉流程 Id(ProcedureModel.Id),
  1470. // 需要在所有 CameraProcedures 的 ProcedureModels 中查找匹配的流程。
  1471. ProcedureModel selectedProcedure = null;
  1472. try
  1473. {
  1474. cameraProcedures = currentProduct.CameraProcedures;
  1475. if (cameraProcedures != null)
  1476. {
  1477. foreach (var cp in cameraProcedures)
  1478. {
  1479. if (cp?.ProcedureModels == null) continue;
  1480. selectedProcedure = cp.ProcedureModels.FirstOrDefault(pm => pm.Id == targetPoint.CameraProcedureId1);
  1481. if (selectedProcedure != null) break;
  1482. }
  1483. }
  1484. }
  1485. catch (Exception ex)
  1486. {
  1487. LogHelper.WriteLogError("查找 AOI 点位对应视觉流程时出错", ex);
  1488. }
  1489. if (selectedProcedure == null)
  1490. {
  1491. SendTaskMessage($"未找到 AOI 点位对应的视觉流程,Point#{cameraIndex} ProcedureId={targetPoint.CameraProcedureId1}", MessageLevel.Alarm);
  1492. await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)2);
  1493. return;
  1494. }
  1495. if (selectedProcedure.Id == currentProduct.FixedDownCameraProcedureId && sysConfig.TurnOnAllLightUse == true)
  1496. {
  1497. await _remoteCommandService.SetLightBeforePhoto(selectedProcedure);
  1498. }
  1499. if(sysConfig.ScannerUse==false)
  1500. {
  1501. var visionResult = await _remoteCommandService.ExecutePhotoGetSinglePoint2(selectedProcedure, null, null, cts.Token);
  1502. if (visionResult.IsSucceed)
  1503. {
  1504. code = visionResult.X.ToUpper();
  1505. SendTaskMessage($"扫码成功,SN:{code}", MessageLevel.Info);
  1506. //这里缺少从MES获取产品配方的内容,需要补充
  1507. _LastMesCheckTime[0] = (await _mesService.GetServerTimeAsync(code, 2)).Now;
  1508. LogHelper.WriteLogMes($"【mes开始QUERY】");
  1509. SendTaskMessage($"mes开始QUERY", MessageLevel.Info);
  1510. //(bool isSuccess, string response) = await _mesService.StationGetAsync(code, "", 2);//询问mes
  1511. (bool isSuccess, string response) = await _mesService.StationGetExAsync(code, "", 2);//基于电池的SN获取产品SN,询问mes
  1512. if (isSuccess)
  1513. {
  1514. //产品发生改变并且供料器发生了变化时,需要通知PLC进行取料更改
  1515. string ProductMainSN_Temp = "";
  1516. LogHelper.WriteLogMes($"询问mes成功");
  1517. SendTaskMessage($"询问mes成功:{response}", MessageLevel.Debug);
  1518. if (response != "MES功能未启用!")
  1519. {
  1520. string[] item = response.Split('\n');
  1521. if (item[2].Contains("sn="))
  1522. {
  1523. ProductMainSN_Temp = item[2].Replace("sn=", "");
  1524. SendTaskMessage($"sn:{ProductMainSN_Temp}", MessageLevel.Info);
  1525. }
  1526. }
  1527. LogHelper.WriteLogMes($"询问mes成功");
  1528. SendTaskMessage($"询问mes成功:{response}", MessageLevel.Debug);
  1529. //20260214,特别版(电池组装)
  1530. (bool isSuccess2, string response2) = await _mesService.StationGetAsync(ProductMainSN_Temp, "", 2);//询问mes
  1531. if (isSuccess2)
  1532. {
  1533. LogHelper.WriteLogMes($"询问mes成功");
  1534. SendTaskMessage($"询问mes成功:{response2}", MessageLevel.Debug);
  1535. if (response2 != "MES功能未启用!")
  1536. {
  1537. string[] item = response2.Split('\n');
  1538. if (item[3].Contains("sn="))
  1539. {
  1540. ProductMainSN = item[3].Replace("sn=", "");
  1541. _productService.CurrentProductCode = ProductMainSN;
  1542. SendTaskMessage($"产品主sn:{ProductMainSN}", MessageLevel.Info);
  1543. }
  1544. if (item[5].Contains("wo="))
  1545. {
  1546. wo = item[5].Replace("wo=", "");
  1547. SendTaskMessage($"产品主wo:{wo}", MessageLevel.Info);
  1548. }
  1549. }
  1550. LogHelper.WriteLogMes($"第二次询问mes成功");
  1551. SendTaskMessage($"第二次询问mes成功:{response2}", MessageLevel.Debug);
  1552. await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)1);
  1553. }
  1554. else
  1555. {
  1556. LogHelper.WriteLogMes($"第二次询问mes失败");
  1557. SendTaskMessage($"第二次询问mes失败:{response2}", MessageLevel.Error);
  1558. await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)3);
  1559. }
  1560. }
  1561. else
  1562. {
  1563. //产品发生改变并且供料器发生了变化时,需要通知PLC进行取料更改
  1564. await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)3);
  1565. LogHelper.WriteLogMes($"询问mes失败");
  1566. SendTaskMessage($"询问mes失败:{response}", MessageLevel.Error);
  1567. }
  1568. }
  1569. else
  1570. {
  1571. SendTaskMessage($"扫码失败", MessageLevel.Alarm);
  1572. await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)3);
  1573. }
  1574. }
  1575. else
  1576. {
  1577. code = visionResult.X.ToUpper();
  1578. SendTaskMessage($"扫码成功,SN:{code}", MessageLevel.Info);
  1579. //这里缺少从MES获取产品配方的内容,需要补充
  1580. _LastMesCheckTime[0] = (await _mesService.GetServerTimeAsync(code, 2)).Now;
  1581. LogHelper.WriteLogMes($"【mes开始QUERY】");
  1582. SendTaskMessage($"mes开始QUERY", MessageLevel.Info);
  1583. //(bool isSuccess, string response) = await _mesService.StationGetAsync(code, "", 2);//询问mes
  1584. (bool isSuccess, string response) = await _mesService.StationGetExAsync(code, "", 2);//基于电池的SN获取产品SN,询问mes
  1585. if (isSuccess)
  1586. {
  1587. //产品发生改变并且供料器发生了变化时,需要通知PLC进行取料更改
  1588. string ProductMainSN_Temp = "";
  1589. LogHelper.WriteLogMes($"询问mes成功");
  1590. SendTaskMessage($"询问mes成功:{response}", MessageLevel.Debug);
  1591. if (response != "MES功能未启用!")
  1592. {
  1593. string[] item = response.Split('\n');
  1594. if (item[2].Contains("sn="))
  1595. {
  1596. ProductMainSN_Temp = item[2].Replace("sn=", "");
  1597. SendTaskMessage($"sn:{ProductMainSN_Temp}", MessageLevel.Info);
  1598. }
  1599. }
  1600. LogHelper.WriteLogMes($"询问mes成功");
  1601. SendTaskMessage($"询问mes成功:{response}", MessageLevel.Debug);
  1602. //20260214,特别版(电池组装)
  1603. (bool isSuccess2, string response2) = await _mesService.StationGetAsync(ProductMainSN_Temp, "", 2);//询问mes
  1604. if (isSuccess2)
  1605. {
  1606. LogHelper.WriteLogMes($"询问mes成功");
  1607. SendTaskMessage($"询问mes成功:{response2}", MessageLevel.Debug);
  1608. if (response2 != "MES功能未启用!")
  1609. {
  1610. string[] item = response2.Split('\n');
  1611. if (item[3].Contains("sn="))
  1612. {
  1613. ProductMainSN = item[3].Replace("sn=", "");
  1614. _productService.CurrentProductCode = ProductMainSN;
  1615. SendTaskMessage($"产品主sn:{ProductMainSN}", MessageLevel.Info);
  1616. }
  1617. if (item[5].Contains("wo="))
  1618. {
  1619. wo = item[5].Replace("wo=", "");
  1620. SendTaskMessage($"产品主wo:{wo}", MessageLevel.Info);
  1621. }
  1622. }
  1623. LogHelper.WriteLogMes($"第二次询问mes成功");
  1624. SendTaskMessage($"第二次询问mes成功:{response2}", MessageLevel.Debug);
  1625. await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)1);
  1626. }
  1627. else
  1628. {
  1629. LogHelper.WriteLogMes($"第二次询问mes失败");
  1630. SendTaskMessage($"第二次询问mes失败:{response2}", MessageLevel.Error);
  1631. await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)3);
  1632. }
  1633. }
  1634. else
  1635. {
  1636. //产品发生改变并且供料器发生了变化时,需要通知PLC进行取料更改
  1637. await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)3);
  1638. LogHelper.WriteLogMes($"询问mes失败");
  1639. SendTaskMessage($"询问mes失败:{response}", MessageLevel.Error);
  1640. }
  1641. }
  1642. return;
  1643. }
  1644. if (sysConfig.CodeUse2 == true && cameraIndex == 1)
  1645. {
  1646. var cts = new CancellationTokenSource();
  1647. // CameraProcedureId 存储的是具体的视觉流程 Id(ProcedureModel.Id),
  1648. // 需要在所有 CameraProcedures 的 ProcedureModels 中查找匹配的流程。
  1649. ProcedureModel selectedProcedure = null;
  1650. try
  1651. {
  1652. cameraProcedures = currentProduct.CameraProcedures;
  1653. if (cameraProcedures != null)
  1654. {
  1655. foreach (var cp in cameraProcedures)
  1656. {
  1657. if (cp?.ProcedureModels == null) continue;
  1658. selectedProcedure = cp.ProcedureModels.FirstOrDefault(pm => pm.Id == targetPoint.CameraProcedureId1);
  1659. if (selectedProcedure != null) break;
  1660. }
  1661. }
  1662. }
  1663. catch (Exception ex)
  1664. {
  1665. LogHelper.WriteLogError("查找 AOI 点位对应视觉流程时出错", ex);
  1666. }
  1667. if (selectedProcedure == null)
  1668. {
  1669. SendTaskMessage($"未找到 AOI 点位对应的视觉流程,Point#{cameraIndex} ProcedureId={targetPoint.CameraProcedureId1}", MessageLevel.Alarm);
  1670. await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)2);
  1671. return;
  1672. }
  1673. var ctsAll = new CancellationTokenSource();
  1674. if (selectedProcedure.Id == currentProduct.FixedDownCameraProcedureId && sysConfig.TurnOnAllLightUse == true)
  1675. {
  1676. await _remoteCommandService.SetLightBeforePhoto(selectedProcedure);
  1677. }
  1678. var visionResult = await _remoteCommandService.ExecutePhotoGetSinglePoint2(selectedProcedure, null, null, ctsAll.Token);
  1679. if (visionResult.IsSucceed)
  1680. {
  1681. code = visionResult.X;
  1682. ProductMainSN = visionResult.X;
  1683. SendTaskMessage($"扫码成功,SN:{code}", MessageLevel.Info);
  1684. //这里缺少从MES获取产品配方的内容,需要补充
  1685. _LastMesCheckTime[0] = (await _mesService.GetServerTimeAsync(code, 2)).Now;
  1686. //_LastMesCheckTime[1] = DateTime.Now;
  1687. LogHelper.WriteLogMes($"【mes开始QUERY】");
  1688. SendTaskMessage($"mes开始QUERY", MessageLevel.Info);
  1689. (bool isSuccess, string response) = await _mesService.StationGetAsync(code, "", 2);//询问mes
  1690. if (isSuccess)
  1691. {
  1692. //产品发生改变并且供料器发生了变化时,需要通知PLC进行取料更改
  1693. LogHelper.WriteLogMes($"询问mes成功");
  1694. SendTaskMessage($"询问mes成功:{response}", MessageLevel.Debug);
  1695. if (response != "MES功能未启用!")
  1696. {
  1697. string[] items = response.Split('\n');
  1698. if (items[3].Contains("sn="))
  1699. {
  1700. ProductMainSN = items[3].Replace("sn=", "");
  1701. _productService.CurrentProductCode = ProductMainSN;
  1702. }
  1703. SendTaskMessage($"产品主sn:{ProductMainSN}", MessageLevel.Info);
  1704. if (items[5].Contains("wo="))
  1705. {
  1706. wo = items[5].Replace("wo=", "");
  1707. }
  1708. SendTaskMessage($"产品wo:{wo}", MessageLevel.Info);
  1709. }
  1710. LogHelper.WriteLogMes($"【mes结束QUERY】");
  1711. SendTaskMessage($"mes结束QUERY", MessageLevel.Info);
  1712. await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)1);
  1713. return;
  1714. }
  1715. else
  1716. {
  1717. //产品发生改变并且供料器发生了变化时,需要通知PLC进行取料更改
  1718. await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)3);
  1719. LogHelper.WriteLogMes($"询问mes失败");
  1720. SendTaskMessage($"询问mes失败:{response}", MessageLevel.Error);
  1721. }
  1722. }
  1723. else
  1724. {
  1725. SendTaskMessage($"扫码失败", MessageLevel.Alarm);
  1726. await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)3);
  1727. }
  1728. return;
  1729. }
  1730. foreach (var prcId in procIds)
  1731. {
  1732. if (Is3D(prcId))
  1733. {
  1734. _PrcTaskList.Add(ExecuteProcedureAsync(cameraIndex, prcId));
  1735. }
  1736. else
  1737. {
  1738. //2d相机时,需要先等待图像采集完成
  1739. var imageData = await GrabImage(cameraIndex, prcId);
  1740. if (imageData.IsSucceed)
  1741. {
  1742. _PrcTaskList.Add(ExecuteProcedureAsync(cameraIndex, prcId, imageData.imges));
  1743. }
  1744. else
  1745. {
  1746. SendTaskMessage($"图像采集失败!{cameraIndex}: {prcId}", MessageLevel.Alarm);
  1747. }
  1748. }
  1749. }
  1750. //如果最后一个拍照点,则需要等待前面所有的拍照处理完成
  1751. if (cameraIndex == currentProduct.PhotoCountStop)
  1752. {
  1753. //等待所有的图像处理流程处理完成
  1754. var results = await Task.WhenAll(_PrcTaskList);
  1755. //结果输出
  1756. bool resultFlog = true;
  1757. foreach (var item in results)
  1758. {
  1759. if (!item.IsSucceed || item.Result == null)
  1760. {
  1761. resultFlog = false;
  1762. }
  1763. else
  1764. {
  1765. foreach (var item_1 in item.Result)
  1766. {
  1767. if (!item_1)
  1768. {
  1769. resultFlog = false;
  1770. break;
  1771. }
  1772. }
  1773. }
  1774. }
  1775. //全部OK
  1776. if (resultFlog)
  1777. {
  1778. SendTaskMessage($"检测执行成功", MessageLevel.Debug);
  1779. await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)1);
  1780. }
  1781. //存在NG
  1782. else
  1783. {
  1784. SendTaskMessage($"检测执行失败", MessageLevel.Alarm);
  1785. await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)2);
  1786. }
  1787. }
  1788. else
  1789. {
  1790. //直接放行,执行下一个检测点
  1791. //SendTaskMessage($"流程执行成功", MessageLevel.Info);
  1792. await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)1);
  1793. }
  1794. }
  1795. else
  1796. {
  1797. SendTaskMessage($"触发固定相机检测拍照信号已关闭", MessageLevel.Alarm);
  1798. await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)0);
  1799. }
  1800. }
  1801. }
  1802. // 过站检查
  1803. else
  1804. {
  1805. for (int i = 0; i < 10; i++)
  1806. {
  1807. if (string.Format(addressConfig.In_MesCheck.Address, i).Contains(tuple.nodeId))
  1808. {
  1809. if (tuple.value is Int16 state)
  1810. {
  1811. if (_LastMesCheck[i] != state)
  1812. {
  1813. _LastMesCheck[i] = state;
  1814. }
  1815. else
  1816. {
  1817. return;
  1818. }
  1819. var sysConfig = _configService.GetSystemConfiguration();
  1820. if (sysConfig.CodeUse == true && state == 1)
  1821. {
  1822. await plc.WriteNodeAsync(string.Format(addressConfig.Out_MesStatus.Address, i), (Int16)1);
  1823. return;
  1824. }
  1825. if (sysConfig.CodeUse2 == true && state == 1)
  1826. {
  1827. await plc.WriteNodeAsync(string.Format(addressConfig.Out_MesStatus.Address, i), (Int16)1);
  1828. return;
  1829. }
  1830. if (sysConfig.CodeUse == false && sysConfig.CodeUse2 == false)
  1831. {
  1832. code = plc.ReadNode<string>(string.Format(addressConfig.In_Code.Address, i));
  1833. }
  1834. var homeview = _container.Resolve<HomeViewModel>();
  1835. //过站检查
  1836. if (state == 1)
  1837. {
  1838. //这里缺少从MES获取产品配方的内容,需要补充
  1839. _LastMesCheckTime[i] = (await _mesService.GetServerTimeAsync(code, 2)).Now;
  1840. LogHelper.WriteLogMes($"【mes开始QUERY】");
  1841. SendTaskMessage($"mes开始QUERY", MessageLevel.Info);
  1842. ShowMes_Query = false;
  1843. (bool isSuccess, string response) = await _mesService.StationGetAsync(code, "", 2);//询问mes
  1844. if (i == 0)
  1845. {
  1846. SendTaskMessage($"收到当前过站检查请求(当站是否生产)...", MessageLevel.Debug);
  1847. }
  1848. else
  1849. {
  1850. SendTaskMessage($"收到{i}过站检查请求(当站是否生产)...", MessageLevel.Debug);
  1851. }
  1852. if (isSuccess)
  1853. {
  1854. string[] item = response.Split('\n');
  1855. //获取产品主sn和wo用于后续上传数据使用
  1856. string snItem = item.FirstOrDefault(f => f.Contains("sn="));
  1857. if (snItem != null)
  1858. {
  1859. ProductMainSN = snItem.Replace("sn=", "").Trim();
  1860. if (i == 0)
  1861. {
  1862. _productService.CurrentProductCode = ProductMainSN;
  1863. }
  1864. SendTaskMessage($"产品主sn:{ProductMainSN[i]}", MessageLevel.Info);
  1865. }
  1866. string woItem = item.FirstOrDefault(f => f.Contains("wo="));
  1867. if (woItem != null)
  1868. {
  1869. wo = woItem.Replace("wo=", "").Trim();
  1870. SendTaskMessage($"工单信息:{wo[i]}", MessageLevel.Info);
  1871. }
  1872. ShowMes_Query = true;
  1873. //产品发生改变并且供料器发生了变化时,需要通知PLC进行取料更改
  1874. await plc.WriteNodeAsync(string.Format(addressConfig.Out_MesStatus.Address, i), (Int16)1);
  1875. LogHelper.WriteLogMes($"【mes结束QUERY】");
  1876. SendTaskMessage($"mes结束QUERY", MessageLevel.Info);
  1877. return;
  1878. }
  1879. else
  1880. {
  1881. //产品发生改变并且供料器发生了变化时,需要通知PLC进行取料更改
  1882. await plc.WriteNodeAsync(string.Format(addressConfig.Out_MesStatus.Address, i), (Int16)2);
  1883. LogHelper.WriteLogMes($"询问mes失败");
  1884. SendTaskMessage($"询问mes失败:{response}", MessageLevel.Error);
  1885. }
  1886. LogHelper.WriteLogMes($"【mes结束QUERY】");
  1887. SendTaskMessage($"mes结束QUERY", MessageLevel.Info);
  1888. }
  1889. // 上传本站数据
  1890. else if (state == 2)
  1891. {
  1892. //获取当前工位的配置
  1893. var stationConfig = _configService.GetDeviceInfo();
  1894. List<DataFormCtq> DFC = new List<DataFormCtq>();
  1895. SendTaskMessage($"收到{i}上传本站数据请求...", MessageLevel.Debug);
  1896. //这里缺少上传MES的本站数据结果及开始和结束时间,需要补充
  1897. //从服务器中获取当前时间
  1898. var serverTimeResult = await _mesService.GetServerTimeAsync(code, 2);
  1899. double ct = serverTimeResult.Now.Subtract(_LastMesCheckTime[i]).TotalSeconds;
  1900. if (i == 0)
  1901. {
  1902. CTtime = ct;
  1903. }
  1904. //读取产品结果
  1905. Int16 resultIndex = plc.ReadNode<Int16>(string.Format(addressConfig.In_Result.Address, i));
  1906. if (homeview.IsResultTrue == false)
  1907. {
  1908. resultIndex = 1;
  1909. }
  1910. //Int16 resultIndex = 1;
  1911. //目前只记录当前站
  1912. if (i == 0)
  1913. await _systemDatabaseService.RecordProductionAsync(new ProductionRecord()
  1914. {
  1915. ProductName = currentProduct.Name,
  1916. ProductCode = code,
  1917. DeviceId = i,
  1918. DeviceName = "",
  1919. Category = resultIndex == 1 ? "OK" : "NG",
  1920. Quantity = 1,
  1921. Remark = $"TotalSeconds:{DateTime.UtcNow.Subtract(_LastMesCheckTime[i]).TotalSeconds.ToString("F2")}",
  1922. });
  1923. LogHelper.WriteLogMes($"【mes开始ADD】");
  1924. SendTaskMessage($"mes开始ADD", MessageLevel.Info);
  1925. StringBuilder submitData = new StringBuilder();
  1926. foreach (var item in lockResultsAll)
  1927. {
  1928. submitData.Append($"{item.PhotoName}-{item.ResultData}");
  1929. }
  1930. ShowMes_Result = resultIndex == 1 ? true : false;
  1931. //(bool isSuccess, string response) = await _mesService.SubmitGetAsync(ProductMainSN, "", MesData.Replace("--", "-"), resultIndex == 1 ? true : false, _LastMesCheckTime[i], DateTime.UtcNow);
  1932. (bool isSuccess, string response) = await _mesService.SubmitGetAsync(ProductMainSN, "", submitData.ToString(), resultIndex == 1 ? true : false, _LastMesCheckTime[i], serverTimeResult.Now);
  1933. if (isSuccess)
  1934. {
  1935. LogHelper.WriteLogMes($"上传mes成功");
  1936. SendTaskMessage($"上传mes成功", MessageLevel.Debug);
  1937. //ProductMainSN = "";
  1938. }
  1939. else
  1940. {
  1941. LogHelper.WriteLogMes($"上传mes失败");
  1942. SendTaskMessage($"上传mes失败", MessageLevel.Error);
  1943. //ProductMainSN = "";
  1944. }
  1945. await plc.WriteNodeAsync(string.Format(addressConfig.Out_MesStatus.Address, i), (Int16)3);
  1946. //是否保存当前的产品记录至CSV?
  1947. if (stationConfig.SaveCsv)
  1948. {
  1949. //判断锁付路径字符串是否为空,如果不为空则保存,否则不保存
  1950. if (!string.IsNullOrEmpty(stationConfig.SaveCsvPath))
  1951. {
  1952. foreach (var item in lockResultsAll)
  1953. {
  1954. DFC.Add(new DataFormCtq
  1955. {
  1956. PPID = ProductMainSN,
  1957. PROCESS_NAME = stationConfig.DataInfo.PROCESS_NAME,
  1958. PROCESS_START_TIME = _LastMesCheckTime[i].ToString(),
  1959. CTQ_NAME = item.PhotoName,
  1960. CTQ_VALUE = item.ResultData.Replace(",", ";"),
  1961. CTQ_LSL = item.DownLimit,
  1962. CTQ_USL = item.UpLimit,
  1963. PROCESS_END_TIME = serverTimeResult.Now.ToString(),
  1964. SUPPLIER_NAME = stationConfig.DataInfo.SUPPLIER_NAME,
  1965. COMMODITY_TYPE = stationConfig.DataInfo.COMMODITY_TYPE,
  1966. REVISION = stationConfig.DataInfo.REVISION,
  1967. WO = wo,
  1968. MFG_LOT = stationConfig.DataInfo.MFG_LOT,
  1969. MFG_ASSY_LINE = stationConfig.DataInfo.MFG_ASSY_LINE,
  1970. PROCESS_OUTCOME = item.PhotoPassed == "OK" ? "PASS" : "FAIL",
  1971. PROCESS_MACHINE_ID = stationConfig.DataInfo.PROCESS_MACHINE_ID,
  1972. CTQ_UNIT_OF_MEASURE = "mm",
  1973. ERROR_MESSAGE = item.PhotoPassed == "OK" ? "" : $"{item.PhotoName} OOS",
  1974. PD_ATTR_01= "xxxxxxxx1",
  1975. PD_ATTR_02 = item.MidLimit,
  1976. PD_ATTR_03 = "",
  1977. PD_ATTR_04 = "",
  1978. PD_ATTR_05 = ""
  1979. });
  1980. }
  1981. bool recordResult = RecordStationResult(i, DFC, ProductMainSN, serverTimeResult.Now.Subtract(_LastMesCheckTime[i]).TotalSeconds, _LastMesCheckTime[i], stationConfig.SaveCsvPath);
  1982. if (recordResult)
  1983. {
  1984. SendTaskMessage($"{i}:{stationConfig.DeviceName}产品记录保存成功", MessageLevel.Debug);
  1985. }
  1986. else
  1987. {
  1988. SendTaskMessage($"{i}:{stationConfig.DeviceName}产品记录保存失败", MessageLevel.Error);
  1989. }
  1990. }
  1991. else
  1992. {
  1993. SendTaskMessage($"{i}:{stationConfig.DeviceName}工位未配置保存路径,无法保存产品记录", MessageLevel.Error);
  1994. }
  1995. }
  1996. else
  1997. {
  1998. SendTaskMessage($"{i}:{stationConfig.DeviceName}工位未配置保存产品记录", MessageLevel.Debug);
  1999. }
  2000. //WriteProductLog(lockResultsAll, code, CTtime);
  2001. lock (_stateLock)
  2002. {
  2003. lockResultsAll.Clear();
  2004. }
  2005. ProductMainSN = "";
  2006. LogHelper.WriteLogMes($"【mes结束ADD】");
  2007. SendTaskMessage($"mes结束ADD", MessageLevel.Info);
  2008. }
  2009. else
  2010. {
  2011. SendTaskMessage($"{i}过站检查信号:state={state},处理为默认状态", MessageLevel.Alarm);
  2012. await plc.WriteNodeAsync(string.Format(addressConfig.Out_MesStatus.Address, i), (Int16)0);
  2013. }
  2014. }
  2015. }
  2016. }
  2017. }
  2018. }
  2019. catch (Exception ex)
  2020. {
  2021. SendTaskMessage(ex.Message, MessageLevel.Error);
  2022. }
  2023. }
  2024. /// <summary>
  2025. /// 异步执行流程拍照
  2026. /// </summary>
  2027. /// <param name="pointIndex"></param>
  2028. /// <param name="procedureId"></param>
  2029. /// <returns></returns>
  2030. private Task<(bool IsSucceed, bool[] Result, string Message)> ExecuteProcedureAsync(int pointIndex, Guid procedureId)
  2031. {
  2032. return Task.Run(async () =>
  2033. {
  2034. List<bool> results = new List<bool>();
  2035. // 获取当前产品
  2036. var currentProduct = _productService.GetCurrentProduct();
  2037. if (currentProduct == null)
  2038. {
  2039. return (false, null, "当前产品为空,未加载产品!");
  2040. }
  2041. var cameraProcedures = currentProduct.CameraProcedures;
  2042. if (cameraProcedures == null || cameraProcedures.Count == 0)
  2043. {
  2044. SendTaskMessage($"当前产品未配置 CameraProcedures,无法执行视觉流程", MessageLevel.Alarm);
  2045. return (false, null, $"当前产品未配置 CameraProcedures,无法执行视觉流程");
  2046. }
  2047. var ctsAll = new CancellationTokenSource();
  2048. try
  2049. {
  2050. ProcedureModel selectedProcedure = null;
  2051. try
  2052. {
  2053. foreach (var cp in cameraProcedures)
  2054. {
  2055. if (cp?.ProcedureModels == null) continue;
  2056. selectedProcedure = cp.ProcedureModels.FirstOrDefault(pm => pm.Id == procedureId);
  2057. if (selectedProcedure != null) break;
  2058. }
  2059. }
  2060. catch (Exception ex)
  2061. {
  2062. LogHelper.WriteLogError("查找 AOI 点位对应视觉流程时出错", ex);
  2063. }
  2064. if (selectedProcedure == null)
  2065. {
  2066. SendTaskMessage($"未找到 AOI 点位对应的视觉流程,Point#{pointIndex} ProcedureId={pointIndex}", MessageLevel.Alarm);
  2067. return (false, null, $"未找到 AOI 点位对应的视觉流程,Point#{pointIndex} ProcedureId={procedureId}");
  2068. }
  2069. SendTaskMessage($"开始执行 AOI 流程 (Point#{pointIndex}) 流程Id={pointIndex}", MessageLevel.Debug);
  2070. try
  2071. {
  2072. //1. 执行拍照,图像处理
  2073. var visionResult = await _remoteCommandService.ExecutePhotoGetSinglePoint1(selectedProcedure, null, null, ctsAll.Token);
  2074. if (visionResult.Count == 0)
  2075. {
  2076. SendTaskMessage("Count值为0", MessageLevel.Alarm);
  2077. return (false, null, $"未找到 AOI 点位对应的视觉流程,Point#{pointIndex} ProcedureId={procedureId}");
  2078. }
  2079. //2. 结果分析
  2080. for (int i = 1; i <= visionResult.Count; i++)
  2081. {
  2082. LockResult lockResult1 = new LockResult();
  2083. //if (pointIndex == currentProduct.PhotoCount && selectedProcedure.Id == currentProduct.FixedUpCamera1ProcedureId && i == 1)
  2084. //{
  2085. // lockResult1.Number = 1;
  2086. //}
  2087. string[] strpoints1 = visionResult.Items[i].Split(',');
  2088. lockResult1.PhotoName = strpoints1[0];
  2089. string[] body1 = strpoints1[1].Split(";");
  2090. string body2 = null;
  2091. if (body1.Length == 8)
  2092. {
  2093. body2 = $"{body1[0]},{body1[2]},{body1[4]},{body1[6]}";
  2094. }
  2095. else
  2096. {
  2097. body2 = strpoints1[1];
  2098. }
  2099. lockResult1.ResultData = body2;
  2100. lockResult1.PhotoCode = ProductMainSN;
  2101. var globalParam = currentProduct.GlobalParamListCollection.FirstOrDefault(p => p.Name == strpoints1[0]);
  2102. if (globalParam != null)
  2103. {
  2104. lockResult1.UpLimit = globalParam.Param1;
  2105. lockResult1.DownLimit = globalParam.Param2;
  2106. lockResult1.MidLimit = globalParam.Param5;
  2107. string ResData = strpoints1[1];
  2108. if (ResData.Contains("NA"))
  2109. {
  2110. ResData = "-1000";
  2111. }
  2112. string[] body = ResData.Split(";");
  2113. bool resultflog = true;
  2114. foreach (var item in body)
  2115. {
  2116. if (Convert.ToDouble(item) >= Convert.ToDouble(globalParam.Param2) && Convert.ToDouble(item) <= Convert.ToDouble(globalParam.Param1))
  2117. {
  2118. }
  2119. else
  2120. {
  2121. resultflog = false;
  2122. }
  2123. }
  2124. if (resultflog)
  2125. {
  2126. lockResult1.PhotoPassed = "OK";
  2127. results.Add(true);
  2128. }
  2129. else
  2130. {
  2131. lockResult1.PhotoPassed = "NG";
  2132. results.Add(false);
  2133. }
  2134. }
  2135. lock (_stateLock)
  2136. {
  2137. lockResultsAll.Add(lockResult1);
  2138. }
  2139. App.Current.Dispatcher.Invoke(() =>
  2140. {
  2141. _eventAggregator.GetEvent<LockFinishNotification>().Publish(lockResult1);
  2142. });
  2143. }
  2144. //排序
  2145. //lock (_stateLock)
  2146. //{
  2147. // var bf1 = lockResultsAll.OrderBy(p => p.Number);
  2148. // lockResultsAll = new List<LockResult>(bf1);
  2149. //}
  2150. }
  2151. catch (Exception ex)
  2152. {
  2153. LogHelper.WriteLogError("执行 AOI 视觉流程时出错", ex);
  2154. SendTaskMessage($"执行 AOI 视觉流程异常: {ex.Message}", MessageLevel.Alarm);
  2155. }
  2156. return (true, results.ToArray(), $"成功");
  2157. }
  2158. catch (Exception ex)
  2159. {
  2160. LogHelper.WriteLogError("处理固定相机检测拍照时出错", ex);
  2161. return (false, null, $"处理固定相机检测拍照时出错");
  2162. }
  2163. });
  2164. }
  2165. /// <summary>
  2166. /// 异步执行流程拍照
  2167. /// </summary>
  2168. /// <param name="pointIndex"></param>
  2169. /// <param name="procedureId"></param>
  2170. /// <returns></returns>
  2171. private Task<(bool IsSucceed, bool[] Result, string Message)> ExecuteProcedureAsync(int pointIndex, Guid procedureId, ICogImage[] images)
  2172. {
  2173. return Task.Run(async () =>
  2174. {
  2175. List<bool> results = new List<bool>();
  2176. // 获取当前产品
  2177. var currentProduct = _productService.GetCurrentProduct();
  2178. if (currentProduct == null)
  2179. {
  2180. return (false, null, "当前产品为空,未加载产品!");
  2181. }
  2182. var cameraProcedures = currentProduct.CameraProcedures;
  2183. if (cameraProcedures == null || cameraProcedures.Count == 0)
  2184. {
  2185. SendTaskMessage($"当前产品未配置 CameraProcedures,无法执行视觉流程", MessageLevel.Alarm);
  2186. return (false, null, $"当前产品未配置 CameraProcedures,无法执行视觉流程");
  2187. }
  2188. var ctsAll = new CancellationTokenSource();
  2189. try
  2190. {
  2191. ProcedureModel selectedProcedure = null;
  2192. try
  2193. {
  2194. foreach (var cp in cameraProcedures)
  2195. {
  2196. if (cp?.ProcedureModels == null) continue;
  2197. selectedProcedure = cp.ProcedureModels.FirstOrDefault(pm => pm.Id == procedureId);
  2198. if (selectedProcedure != null) break;
  2199. }
  2200. }
  2201. catch (Exception ex)
  2202. {
  2203. LogHelper.WriteLogError("查找 AOI 点位对应视觉流程时出错", ex);
  2204. }
  2205. if (selectedProcedure == null)
  2206. {
  2207. SendTaskMessage($"未找到 AOI 点位对应的视觉流程,Point#{pointIndex} ProcedureId={pointIndex}", MessageLevel.Alarm);
  2208. return (false, null, $"未找到 AOI 点位对应的视觉流程,Point#{pointIndex} ProcedureId={procedureId}");
  2209. }
  2210. SendTaskMessage($"开始执行 AOI 流程 (Point#{pointIndex}) 流程Id={pointIndex}", MessageLevel.Debug);
  2211. try
  2212. {
  2213. var sysConfig = _configService.GetSystemConfiguration();
  2214. if (selectedProcedure.Id == currentProduct.MoveDownCameraLockPhotoProcedureId && sysConfig.TurnOffAllLightUse == true)
  2215. {
  2216. await _remoteCommandService.TurnOffLightAfterPhoto(selectedProcedure);
  2217. }
  2218. //1. 执行拍照,图像处理
  2219. var visionResult = await _remoteCommandService.ExecutePhotoGetSinglePoint1(selectedProcedure, images, null, null, ctsAll.Token);
  2220. if (visionResult.Count == 0)
  2221. {
  2222. SendTaskMessage("Count值为0", MessageLevel.Alarm);
  2223. return (false, null, $"未找到 AOI 点位对应的视觉流程,Point#{pointIndex} ProcedureId={procedureId}");
  2224. }
  2225. //2. 结果分析
  2226. for (int i = 1; i <= visionResult.Count; i++)
  2227. {
  2228. LockResult lockResult1 = new LockResult();
  2229. //if (pointIndex == currentProduct.PhotoCount && selectedProcedure.Id == currentProduct.FixedUpCamera1ProcedureId && i == 1)
  2230. //{
  2231. // lockResult1.Number = 1;
  2232. // lock (_stateLock)
  2233. // {
  2234. // lockResultsAll.Clear();
  2235. // }
  2236. //}
  2237. string[] strpoints1 = visionResult.Items[i].Split(',');
  2238. lockResult1.PhotoName = strpoints1[0];
  2239. string[] body1 = strpoints1[1].Split(";");
  2240. string body2 = null;
  2241. if (body1.Length == 8)
  2242. {
  2243. body2 = $"{body1[0]},{body1[2]},{body1[4]},{body1[6]}";
  2244. }
  2245. else
  2246. {
  2247. body2 = strpoints1[1];
  2248. }
  2249. lockResult1.ResultData = body2;
  2250. lockResult1.PhotoCode = ProductMainSN;
  2251. var globalParam = currentProduct.GlobalParamListCollection.FirstOrDefault(p => p.Name == strpoints1[0]);
  2252. if (globalParam != null)
  2253. {
  2254. lockResult1.UpLimit = globalParam.Param1;
  2255. lockResult1.DownLimit = globalParam.Param2;
  2256. lockResult1.MidLimit = globalParam.Param5;
  2257. string ResData = strpoints1[1];
  2258. if (ResData.Contains("NA"))
  2259. {
  2260. ResData = "-1000";
  2261. }
  2262. string[] body = ResData.Split(";");
  2263. bool resultflog = true;
  2264. foreach (var item in body)
  2265. {
  2266. if (Convert.ToDouble(item) >= Convert.ToDouble(globalParam.Param2) && Convert.ToDouble(item) <= Convert.ToDouble(globalParam.Param1))
  2267. {
  2268. }
  2269. else
  2270. {
  2271. resultflog = false;
  2272. }
  2273. }
  2274. if (resultflog)
  2275. {
  2276. lockResult1.PhotoPassed = "OK";
  2277. results.Add(true);
  2278. }
  2279. else
  2280. {
  2281. lockResult1.PhotoPassed = "NG";
  2282. results.Add(false);
  2283. }
  2284. }
  2285. lock (_stateLock)
  2286. {
  2287. lockResultsAll.Add(lockResult1);
  2288. }
  2289. App.Current.Dispatcher.Invoke(() =>
  2290. {
  2291. _eventAggregator.GetEvent<LockFinishNotification>().Publish(lockResult1);
  2292. });
  2293. }
  2294. ////排序
  2295. //lock (_stateLock)
  2296. //{
  2297. // var bf1 = lockResultsAll.OrderBy(p => int.Parse(p.PhotoName));
  2298. // lockResultsAll = new List<LockResult>(bf1);
  2299. //}
  2300. }
  2301. catch (Exception ex)
  2302. {
  2303. LogHelper.WriteLogError("执行 AOI 视觉流程时出错", ex);
  2304. SendTaskMessage($"执行 AOI 视觉流程异常: {ex.Message}", MessageLevel.Alarm);
  2305. }
  2306. return (true, results.ToArray(), $"成功");
  2307. }
  2308. catch (Exception ex)
  2309. {
  2310. LogHelper.WriteLogError("处理固定相机检测拍照时出错", ex);
  2311. return (false, null, $"处理固定相机检测拍照时出错");
  2312. }
  2313. });
  2314. }
  2315. /// <summary>
  2316. /// 是否是3D相机
  2317. /// </summary>
  2318. /// <param name="procedureId"></param>
  2319. /// <returns></returns>
  2320. private bool Is3D(Guid procedureId)
  2321. {
  2322. // 获取当前产品
  2323. var currentProduct = _productService.GetCurrentProduct();
  2324. if (currentProduct == null)
  2325. {
  2326. return false;
  2327. }
  2328. var cameraProcedures = currentProduct.CameraProcedures;
  2329. if (cameraProcedures == null || cameraProcedures.Count == 0)
  2330. {
  2331. return false;
  2332. }
  2333. ProcedureModel selectedProcedure = null;
  2334. try
  2335. {
  2336. foreach (var cp in cameraProcedures)
  2337. {
  2338. if (cp?.ProcedureModels == null) continue;
  2339. selectedProcedure = cp.ProcedureModels.FirstOrDefault(pm => pm.Id == procedureId);
  2340. if (selectedProcedure != null) break;
  2341. }
  2342. }
  2343. catch (Exception ex)
  2344. {
  2345. LogHelper.WriteLogError("查找 AOI 点位对应视觉流程时出错", ex);
  2346. }
  2347. if (selectedProcedure == null)
  2348. {
  2349. return false;
  2350. }
  2351. var camera = _cameraService.GetCamera(selectedProcedure.CameraId);
  2352. if (camera == null)
  2353. {
  2354. return false;
  2355. }
  2356. return camera.Is3D;
  2357. }
  2358. /// <summary>
  2359. /// 2D相机先采集图像
  2360. /// </summary>
  2361. /// <param name="procedureId"></param>
  2362. /// <returns></returns>
  2363. private async Task<(bool IsSucceed, ICogImage[] imges, string Message)> GrabImage(int pointIndex, Guid procedureId)
  2364. {
  2365. // 获取当前产品
  2366. var currentProduct = _productService.GetCurrentProduct();
  2367. if (currentProduct == null)
  2368. {
  2369. return (false, null, "当前产品为空,未加载产品!");
  2370. }
  2371. var cameraProcedures = currentProduct.CameraProcedures;
  2372. if (cameraProcedures == null || cameraProcedures.Count == 0)
  2373. {
  2374. SendTaskMessage($"当前产品未配置 CameraProcedures,无法执行视觉流程", MessageLevel.Alarm);
  2375. return (false, null, $"当前产品未配置 CameraProcedures,无法执行视觉流程");
  2376. }
  2377. try
  2378. {
  2379. ProcedureModel selectedProcedure = null;
  2380. try
  2381. {
  2382. foreach (var cp in cameraProcedures)
  2383. {
  2384. if (cp?.ProcedureModels == null) continue;
  2385. selectedProcedure = cp.ProcedureModels.FirstOrDefault(pm => pm.Id == procedureId);
  2386. if (selectedProcedure != null) break;
  2387. }
  2388. }
  2389. catch (Exception ex)
  2390. {
  2391. LogHelper.WriteLogError("查找 AOI 点位对应视觉流程时出错", ex);
  2392. }
  2393. if (selectedProcedure == null)
  2394. {
  2395. SendTaskMessage($"未找到 AOI 点位对应的视觉流程,Point#{pointIndex} ProcedureId={pointIndex}", MessageLevel.Alarm);
  2396. return (false, null, $"未找到 AOI 点位对应的视觉流程,Point#{pointIndex} ProcedureId={procedureId}");
  2397. }
  2398. SendTaskMessage($"开始执行 AOI 流程 (Point#{pointIndex}) 流程Id={pointIndex}", MessageLevel.Debug);
  2399. try
  2400. {
  2401. var sysConfig = _configService.GetSystemConfiguration();
  2402. if (selectedProcedure.Id == currentProduct.FixedDownCameraProcedureId && sysConfig.TurnOnAllLightUse == true)
  2403. {
  2404. await _remoteCommandService.SetLightBeforePhoto(selectedProcedure);
  2405. }
  2406. //1. 执行拍照
  2407. return await _remoteCommandService.ExecuteGrabImageAsync(selectedProcedure);
  2408. }
  2409. catch (Exception ex)
  2410. {
  2411. LogHelper.WriteLogError("执行 AOI 视觉图像采集时出错", ex);
  2412. SendTaskMessage($"执行 AOI 视觉图像采集时出错: {ex.Message}", MessageLevel.Alarm);
  2413. }
  2414. return (false, null, $"图像采集失败");
  2415. }
  2416. catch (Exception ex)
  2417. {
  2418. LogHelper.WriteLogError("处理固定相机检测拍照时出错", ex);
  2419. return (false, null, $"处理固定相机检测拍照时出错");
  2420. }
  2421. }
  2422. /// <summary>
  2423. /// 为所有相机设置批处理点数(会调用具体相机实现的 SetBatchPoints)
  2424. /// </summary>
  2425. /// <param name="points"></param>
  2426. public void SetBatchPoints(int CameraNum, int points)
  2427. {
  2428. try
  2429. {
  2430. if (points == 0 || points < 0)
  2431. {
  2432. return;
  2433. }
  2434. var cameras = _cameraService.GetCameraByNumber(CameraNum);
  2435. if (cameras == null) return;
  2436. try
  2437. {
  2438. // 优先针对已知的 SSZNCamera 类型直接调用
  2439. if (cameras is TeamAAS_VP.Core.Cameras.SSZNCamera sszn)
  2440. {
  2441. sszn.CameraRevFinish = false;
  2442. sszn.SetBatchPoints(points);
  2443. }
  2444. }
  2445. catch (Exception ex)
  2446. {
  2447. LogHelper.WriteLogError($"SetBatchPoints to camera {cameras?.Name} failed", ex);
  2448. }
  2449. }
  2450. catch (Exception ex)
  2451. {
  2452. LogHelper.WriteLogError("SetBatchPoints failed", ex);
  2453. }
  2454. }
  2455. public void SetBatchPoints(int[] CameraSpoints)
  2456. {
  2457. try
  2458. {
  2459. for (int i = 0; i < CameraSpoints.Length; i++)
  2460. {
  2461. SetBatchPoints(i + 1, CameraSpoints[i]);
  2462. }
  2463. }
  2464. catch (Exception ex)
  2465. {
  2466. LogHelper.WriteLogError("SetBatchPoints failed", ex);
  2467. }
  2468. }
  2469. #endregion
  2470. #region 方法
  2471. private void SendTaskMessage(string msg, MessageLevel level)
  2472. {
  2473. App.Current.Dispatcher.Invoke(() =>
  2474. {
  2475. _eventAggregator.GetEvent<TaskMessageNotification>().Publish(new Models.MessageStruct() { Message = msg, level = level });
  2476. });
  2477. }
  2478. private async void DoYieldTime(object state)
  2479. {
  2480. try
  2481. {
  2482. //获取当前产品
  2483. CurrentProduct= _productService.GetCurrentProduct();
  2484. var currentproduct = _productService.GetCurrentProduct();
  2485. if (currentproduct == null) return;
  2486. TotalQuantity = await _systemDatabaseService.GetOverallProductionAsync(currentproduct.Name);
  2487. TotalQuantityToday = await _systemDatabaseService.GetTodayProductionAsync(currentproduct.Name);
  2488. CurrentUPH = await _systemDatabaseService.GetLastHourProductionAsync(currentproduct.Name);
  2489. NgNumber = await _systemDatabaseService.GetNGProductionAsync (currentproduct.Name);
  2490. Yield = ((double)TotalQuantityToday - (double)NgNumber) / (double)TotalQuantityToday * 100;
  2491. }
  2492. catch (Exception)
  2493. {
  2494. }
  2495. }
  2496. #region vm启动检测
  2497. /// <summary>
  2498. /// 杀死所有VM有关进程
  2499. /// </summary>
  2500. public void KillVMProcess()
  2501. {
  2502. KillProcess("VisionMasterServerApp");
  2503. KillProcess("VisionMaster");
  2504. KillProcess("VmModuleProxy.exe");
  2505. KillProcess("vServerApp.exe");
  2506. }
  2507. /// <summary>
  2508. /// 杀死指定进程名的进程
  2509. /// </summary>
  2510. /// <param name="strKillName"></param>
  2511. public void KillProcess(string strKillName)
  2512. {
  2513. foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcesses())
  2514. {
  2515. if (p.ProcessName.Contains(strKillName))
  2516. {
  2517. try
  2518. {
  2519. p.Kill();
  2520. p.WaitForExit();
  2521. }
  2522. catch (Exception ex)
  2523. {
  2524. LogHelper.WriteLogError($"杀死进程:{strKillName}时失败!", ex);
  2525. }
  2526. }
  2527. }
  2528. }
  2529. #endregion
  2530. /// <summary>
  2531. /// 记录工位的结果,其他工位要存储的数据项按照键值对集合的形式传入,键为数据项名称,值为数据项的值
  2532. /// </summary>
  2533. /// <param name="stationIndex"></param>
  2534. /// <param name="dfcs"></param>
  2535. /// <param name="productMainSN"></param>
  2536. /// <param name="ct"></param>
  2537. /// <param name="timestamp"></param>
  2538. /// <param name="savePath"></param>
  2539. /// <param name="isFirstEnter"></param>
  2540. /// <returns></returns>
  2541. private bool RecordStationResult(int stationIndex, IEnumerable<DataFormCtq> dfcs, string productMainSN, double ct, DateTime timestamp, string savePath, bool isFirstEnter = true)
  2542. {
  2543. try
  2544. {
  2545. //获取当前工位的配置
  2546. var stationConfig = _configService.GetDeviceInfo();
  2547. if (stationConfig == null) return false;
  2548. //如果保存路径为空,则不保存
  2549. if (string.IsNullOrEmpty(savePath)) return false;
  2550. string fullPath = savePath;
  2551. //如果保存路径是一个文件路径,则直接保存,否则按照工位和日期进行保存
  2552. if (File.Exists(savePath) || Path.HasExtension(savePath))
  2553. {
  2554. fullPath = savePath;
  2555. //如果路径不存在,则创建
  2556. // 创建目录
  2557. string directory = Path.GetDirectoryName(fullPath);
  2558. if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
  2559. {
  2560. Directory.CreateDirectory(directory);
  2561. }
  2562. }
  2563. else
  2564. {
  2565. //结果保存至CSV文件,文件名格式:savePath\yyyy-MM\工位编号_工位名称_yyyy-MM-dd.csv
  2566. string datePath = timestamp.ToString("yyyy-MM") + "\\";
  2567. string dirPath = Path.Combine(savePath, datePath);
  2568. if (!Directory.Exists(dirPath)) Directory.CreateDirectory(dirPath);
  2569. string fileName = $"{stationIndex}_{stationConfig.DeviceName}_{timestamp.ToString("yyyy-MM-dd")}.csv";
  2570. fullPath = Path.Combine(dirPath, fileName);
  2571. }
  2572. StringBuilder sb = new StringBuilder();
  2573. if (!File.Exists(fullPath))
  2574. {
  2575. sb.Append("PPID,PROCESS_NAME,PROCESS_START_TIME,CTQ_NAME,CTQ_VALUE,CTQ_LSL,CTQ_USL,PROCESS_END_TIME,SUPPLIER_NAME,COMMODITY_TYPE,REVISION,WO#,MFG_LOT#," +
  2576. "MFG_ASSY_LINE,PROCESS_OUTCOME,PROCESS_MACHINE_ID,CTQ_UNIT_OF_MEASURE,ERROR_MESSAGE,PD_ATTR_01,PD_ATTR_02,PD_ATTR_03,PD_ATTR_04,PD_ATTR_05");
  2577. sb.AppendLine();
  2578. }
  2579. if (dfcs == null || dfcs.Count() == 0)
  2580. {
  2581. return false;
  2582. }
  2583. foreach (var dfc in dfcs)
  2584. {
  2585. sb.Append($"{dfc.PPID},{dfc.PROCESS_NAME},{dfc.PROCESS_START_TIME},{dfc.CTQ_NAME},{dfc.CTQ_VALUE},{dfc.CTQ_LSL},{dfc.CTQ_USL},{dfc.PROCESS_END_TIME},{dfc.SUPPLIER_NAME},{dfc.COMMODITY_TYPE},{dfc.REVISION},{dfc.WO},{dfc.MFG_LOT},{dfc.MFG_ASSY_LINE},{dfc.PROCESS_OUTCOME},{dfc.PROCESS_MACHINE_ID},{dfc.CTQ_UNIT_OF_MEASURE},{dfc.ERROR_MESSAGE},{dfc.PD_ATTR_01},{dfc.PD_ATTR_02},{dfc.PD_ATTR_03},{dfc.PD_ATTR_04},{dfc.PD_ATTR_05}");
  2586. sb.AppendLine();
  2587. }
  2588. // 使用 StreamWriter 以追加模式打开文件
  2589. StreamWriter sw = new StreamWriter(fullPath, true, Encoding.UTF8);
  2590. sw.Write(sb.ToString());
  2591. sw.Close();
  2592. sw.Dispose();
  2593. return true;
  2594. }
  2595. catch (Exception ex)
  2596. {
  2597. if (!isFirstEnter)
  2598. {
  2599. return false;
  2600. }
  2601. LogHelper.WriteLogError("记录其他工位结果时出错!", ex);
  2602. //我希望在这里生成一个临时文件来保存这次的记录,因为如果本地文件被打开时可能会导致无法写入,如果不保存的话可能会丢失这次的记录,所以我想在这里生成一个临时文件来保存这次的记录
  2603. //生成临时文件的路径,格式为savePath\yyyy-MM\工位编号_yyyy-MM-dd_temp\工位编号_yyyy-MM-dd_HH-mm-ss-fff_temp.csv
  2604. string datePath = timestamp.ToString("yyyy-MM") + "\\";
  2605. string tempDirPath = Path.Combine(savePath, datePath, $"{stationIndex}_{timestamp.ToString("yyyy-MM-dd")}_temp");
  2606. string tempFileName = $"{stationIndex}_{timestamp.ToString("yyyy-MM-dd_HH-mm-ss-fff")}_temp.csv";
  2607. RecordStationResult(stationIndex, dfcs, productMainSN, ct, timestamp, tempFileName, false);
  2608. return false;
  2609. }
  2610. }
  2611. #endregion
  2612. // 用于等待“指定相机的下一张图到达”
  2613. private readonly object _imageSyncLock = new object();
  2614. private readonly Dictionary<Guid, TaskCompletionSource<ICogImage>> _nextImageTcsByCamera =
  2615. new Dictionary<Guid, TaskCompletionSource<ICogImage>>();
  2616. private Task<ICogImage> PrepareNextImageWait(Guid cameraId)
  2617. {
  2618. lock (_imageSyncLock)
  2619. {
  2620. var tcs = new TaskCompletionSource<ICogImage>(TaskCreationOptions.RunContinuationsAsynchronously);
  2621. _nextImageTcsByCamera[cameraId] = tcs;
  2622. return tcs.Task;
  2623. }
  2624. }
  2625. public async Task SignalImageArrived(Guid cameraId, ICogImage image)
  2626. {
  2627. await Task.Delay(500);
  2628. TaskCompletionSource<ICogImage> tcs = null;
  2629. lock (_imageSyncLock)
  2630. {
  2631. _nextImageTcsByCamera.TryGetValue(cameraId, out tcs);
  2632. }
  2633. tcs?.TrySetResult(image);
  2634. }
  2635. public async Task<ICogImage> WaitNextImageAsync(Guid cameraId, int timeoutMs, CancellationToken token)
  2636. {
  2637. var waitTask = PrepareNextImageWait(cameraId);
  2638. var completed = await Task.WhenAny(waitTask, Task.Delay(timeoutMs, token)).ConfigureAwait(false);
  2639. if (completed != waitTask) return null;
  2640. return await waitTask.ConfigureAwait(false);
  2641. }
  2642. //public async Task<bool> WaitImageFlagAsync(int cameraNo, int timeoutMs, CancellationToken token)
  2643. //{
  2644. // if (cameraNo < 0 || cameraNo >= ImageData.Length)
  2645. // {
  2646. // SendTaskMessage($"等待相机图像失败:CameraNo={cameraNo} 越界", MessageLevel.Alarm);
  2647. // return false;
  2648. // }
  2649. // var start = DateTime.UtcNow;
  2650. // while (ImageData[cameraNo] == 0)
  2651. // {
  2652. // token.ThrowIfCancellationRequested();
  2653. // if ((DateTime.UtcNow - start).TotalMilliseconds >= timeoutMs)
  2654. // {
  2655. // SendTaskMessage($"等待相机图像超时:CameraNo={cameraNo} Timeout={timeoutMs}ms", MessageLevel.Alarm);
  2656. // return false;
  2657. // }
  2658. // await Task.Delay(100, token).ConfigureAwait(false);
  2659. // }
  2660. // return true;
  2661. //}
  2662. }
  2663. }