Management.cs 206 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201
  1. using Cognex.VisionPro;
  2. using CSScripting;
  3. using NPOI.SS.Formula.Eval;
  4. using NPOI.Util;
  5. //using ICSharpCode.SharpZipLib.Zip;
  6. using Prism.Events;
  7. using Prism.Ioc;
  8. using Prism.Mvvm;
  9. using Prism.Regions;
  10. using SqlSugar.SplitTableExtensions;
  11. using System;
  12. using System.Collections.Generic;
  13. using System.Collections.ObjectModel;
  14. using System.Drawing;
  15. using System.IO;
  16. using System.IO.Compression;
  17. using System.Linq;
  18. using System.Text;
  19. using System.Threading;
  20. using System.Threading.Tasks;
  21. using System.Windows.Media;
  22. using Team.FFFeederService.Interfaces;
  23. using TeamAAS_VP.Core.PLCs;
  24. using TeamAAS_VP.Core.ScrewDriver;
  25. using TeamAAS_VP.Enums;
  26. using TeamAAS_VP.Events;
  27. using TeamAAS_VP.Interfaces;
  28. using TeamAAS_VP.Models;
  29. using TeamAAS_VP.Resources.Languages;
  30. using TeamAAS_VP.ViewModels;
  31. using TeamAAS_VP.ViewModels.Home;
  32. using TouchSocket.Core;
  33. using TouchSocket.SerialPorts;
  34. using TouchSocket.Sockets;
  35. namespace TeamAAS_VP.Core
  36. {
  37. public class Management : BindableBase
  38. {
  39. #region 字段
  40. IRegionManager _regionManager;
  41. IEventAggregator _eventAggregator;
  42. IContainerProvider _container;
  43. IConfigService _configService;
  44. IRobotService _robotService;
  45. IScannerService _scannerService;
  46. ICameraService _cameraService;
  47. IFeederService _feederService;
  48. IPlcService _plcService;
  49. ILightManagerService _lightManagerService;
  50. IProductService _productService;
  51. ICalibrationService _calibrationService;
  52. IRemoteCommandService _remoteCommandService;
  53. ISystemDatabaseService _systemDatabaseService;
  54. IMesService _mesService;
  55. Timer yieldtimer;
  56. private DateTime StartTime = DateTime.Now;
  57. /// <summary>
  58. /// 产品主sn
  59. /// </summary>
  60. string ProductMainSN = "";
  61. /// <summary>
  62. /// 工单信息
  63. /// </summary>
  64. string wo = "";
  65. string model_num = "";//产品model_num
  66. string color = "";//产品color
  67. string ppid = "";//产品ppid
  68. string revision = "";//产品revision
  69. string stage = "";//产品revision
  70. /// <summary>
  71. /// 上次执行上传csv的日期
  72. /// </summary>
  73. private DateTime _lastCompressDate = DateTime.MinValue;
  74. /// <summary>
  75. /// 当天是否上传过csv
  76. /// </summary>
  77. private bool _hasCompressedToday = false;
  78. #endregion
  79. #region 属性
  80. private Guid _defaultScannerId = Guid.Empty;
  81. private volatile TaskCompletionSource<string> _scanTcs; // 最简单:只支持单通道“当前一次扫
  82. public string[] CsvData = new string[50];
  83. public int[] ResultData = new int[200];
  84. public string code = "";
  85. List<LockResult> lockResultsAll = new List<LockResult>();//一个产品的总结果
  86. private ObservableCollection<ShowRender> _Renders;
  87. private double _CTtime;
  88. public int ResultDataCount;
  89. public string PhotoPath = "";
  90. // 扫码结果
  91. private string ScanValue = "";
  92. // 扫码完成事件
  93. private readonly ManualResetEventSlim _scanDoneEvent = new ManualResetEventSlim(false);
  94. //键盘数据
  95. public Dictionary<string, double> keyData;
  96. //键盘差值
  97. public bool isValueOk;
  98. private System.Windows.Media.Brush _StatusBackground;
  99. public System.Windows.Media.Brush StatusBackground
  100. {
  101. get { return _StatusBackground; }
  102. set { SetProperty(ref _StatusBackground, value); }
  103. }
  104. private System.Windows.Media.Brush _RunModelBackground;
  105. public System.Windows.Media.Brush RunModelBackground
  106. {
  107. get { return _RunModelBackground; }
  108. set { SetProperty(ref _RunModelBackground, value); }
  109. }
  110. private System.Windows.Media.Brush _ManualModeBackground;
  111. public System.Windows.Media.Brush ManualModeBackground
  112. {
  113. get { return _ManualModeBackground; }
  114. set { SetProperty(ref _ManualModeBackground, value); }
  115. }
  116. private System.Windows.Media.Brush _ClearModeBackground;
  117. public System.Windows.Media.Brush ClearModeBackground
  118. {
  119. get { return _ClearModeBackground; }
  120. set { SetProperty(ref _ClearModeBackground, value); }
  121. }
  122. private SerialPortClient _Scan_Client;
  123. public SerialPortClient Scan_Client
  124. {
  125. get { return _Scan_Client; }
  126. set { _Scan_Client = value; }
  127. }
  128. private bool _ShowMes_Query;
  129. /// <summary>
  130. /// 显示查询结果
  131. /// </summary>
  132. public bool ShowMes_Query
  133. {
  134. get { return _ShowMes_Query; }
  135. set { SetProperty(ref _ShowMes_Query, value); }
  136. }
  137. private bool _ShowMes_Result;
  138. /// <summary>
  139. /// 显示上传结果
  140. /// </summary>
  141. public bool ShowMes_Result
  142. {
  143. get { return _ShowMes_Result; }
  144. set { SetProperty(ref _ShowMes_Result, value); }
  145. }
  146. /// <summary>
  147. /// ct
  148. /// </summary>
  149. public double CTtime
  150. {
  151. get { return _CTtime; }
  152. set { SetProperty(ref _CTtime, value); }
  153. }
  154. /// <summary>
  155. /// 显示界面
  156. /// </summary>
  157. public ObservableCollection<ShowRender> Renders
  158. {
  159. get { return _Renders; }
  160. set { SetProperty(ref _Renders, value); }
  161. }
  162. private ProductModel _CurrentProduct;
  163. /// <summary>
  164. /// 当前产品
  165. /// </summary>
  166. public ProductModel CurrentProduct
  167. {
  168. get { return _CurrentProduct; }
  169. set { SetProperty(ref _CurrentProduct, value); }
  170. }
  171. public BgCommunicate BgCommunicate { get; private set; }
  172. public BgModbusTcpCommunicate BgModbusTcpCommunicate { get; private set; }
  173. private ObservableCollection<StatusInfo> _Status = new ObservableCollection<StatusInfo>();
  174. /// <summary>
  175. /// 状态栏集合
  176. /// </summary>
  177. public ObservableCollection<StatusInfo> Status
  178. {
  179. get { return _Status; }
  180. set { SetProperty(ref _Status, value); }
  181. }
  182. private Int64 _TotalQuantity;
  183. /// <summary>
  184. /// 总产量
  185. /// </summary>
  186. public Int64 TotalQuantity
  187. {
  188. get { return _TotalQuantity; }
  189. set { SetProperty(ref _TotalQuantity, value); }
  190. }
  191. private Int64 _TotalQuantityToday;
  192. /// <summary>
  193. /// 当天的总产量
  194. /// </summary>
  195. public Int64 TotalQuantityToday
  196. {
  197. get { return _TotalQuantityToday; }
  198. set { SetProperty(ref _TotalQuantityToday, value); }
  199. }
  200. private Int64 _CurrentUPH;
  201. /// <summary>
  202. /// 当前的UPH
  203. /// </summary>
  204. public Int64 CurrentUPH
  205. {
  206. get { return _CurrentUPH; }
  207. set { SetProperty(ref _CurrentUPH, value); }
  208. }
  209. private Int64 _NgNumber;
  210. /// <summary>
  211. /// 当前的NG数量
  212. /// </summary>
  213. public Int64 NgNumber
  214. {
  215. get { return _NgNumber; }
  216. set { SetProperty(ref _NgNumber, value); }
  217. }
  218. private double _Yield;
  219. /// <summary>
  220. /// 当前的NG数量
  221. /// </summary>
  222. public double Yield
  223. {
  224. get { return _Yield; }
  225. set { SetProperty(ref _Yield, value); }
  226. }
  227. private XYD_ScrewDriver _ScrewDriver;
  228. public XYD_ScrewDriver ScrewDriver
  229. {
  230. get { return _ScrewDriver; }
  231. set { SetProperty(ref _ScrewDriver, value); }
  232. }
  233. public Dictionary<string, object> BackupObject { get; set; } = new Dictionary<string, object>();
  234. private ObservableCollection<ProductModel> _ProductList;
  235. public ObservableCollection<ProductModel> ProductList
  236. {
  237. get { return _ProductList; }
  238. set { SetProperty(ref _ProductList, value); }
  239. }
  240. #endregion
  241. #region 命令
  242. #endregion
  243. #region 事件
  244. #endregion
  245. public Management(IRegionManager regionManager, IEventAggregator ea, IContainerProvider container, IConfigService configService,
  246. IRobotService robotService, ICameraService cameraService, IFeederService feederService, IPlcService plcService, IProductService productService,
  247. ICalibrationService calibrationService, IRemoteCommandService remoteCommandService, ISystemDatabaseService systemDatabaseService, ILightManagerService lightManagerService, IMesService mesService, IScannerService scannerService)
  248. {
  249. _regionManager = regionManager;
  250. _eventAggregator = ea;
  251. _container = container;
  252. _configService = configService;
  253. _robotService = robotService;
  254. _scannerService = scannerService;
  255. _cameraService = cameraService;
  256. _feederService = feederService;
  257. _plcService = plcService;
  258. _calibrationService = calibrationService;
  259. yieldtimer = new Timer(DoYieldTime, null, 10000, 1000);
  260. Renders = new ObservableCollection<ShowRender>();
  261. _configService = configService;
  262. _productService = productService;
  263. _remoteCommandService = remoteCommandService;
  264. _systemDatabaseService = systemDatabaseService;
  265. _lightManagerService = lightManagerService;
  266. _mesService = mesService;
  267. _eventAggregator.GetEvent<CurrentStatusNotification>().Subscribe(CurrentRunStatus);
  268. }
  269. #region 初始化硬件模块
  270. /// <summary>
  271. /// 初始化Feeder
  272. /// </summary>
  273. /// <returns></returns>
  274. public async Task<(bool IsSucceed, string Msg)> InitFeeders()
  275. {
  276. var feeders = _configService.GetAllFeeders();
  277. StringBuilder sb = new StringBuilder();
  278. foreach (var item in feeders)
  279. {
  280. _feederService.CreateFeeder(item.Id, item.FeederNo, item.FeederName, item.IP, item.Port, item.FeederBrand);
  281. var feeder = _feederService.GetFeeder(item.Id);
  282. Status.Add(new StatusInfo(item.Id, item.FeederName + $"{Lang.未连接}", new SolidColorBrush(Colors.Red)));
  283. try
  284. {
  285. feeder.FeederConnectionStatusChanged += Management_FeederConnectionStatusChanged;
  286. await feeder.ConnectAsync(); //连接Feeder
  287. //SendTaskMessage($"{item.FeederName}已连接!", MessageLevel.Debug);
  288. }
  289. catch (Exception ex)
  290. {
  291. sb.AppendLine($"{item.FeederName}:{Lang.断开连接}![{ex.Message}]");
  292. SendTaskMessage($"{item.FeederName}{Lang.断开连接}!", MessageLevel.Alarm);
  293. }
  294. }
  295. if (sb.Length == 0)
  296. {
  297. return (true, "");
  298. }
  299. else
  300. {
  301. return (false, sb.ToString());
  302. }
  303. }
  304. /// <summary>
  305. /// 初始化机器人
  306. /// </summary>
  307. /// <returns></returns>
  308. public async Task<(bool IsSucceed, string Msg)> InitRobots()
  309. {
  310. var robots = _configService.GetAllRobots();
  311. StringBuilder sb = new StringBuilder();
  312. foreach (var item in robots)
  313. {
  314. _robotService.CreateRobot(item.Id, item);
  315. try
  316. {
  317. Status.Add(new StatusInfo(item.Id, item.RobotName + $"{Lang.未连接}", new SolidColorBrush(Colors.Red)));
  318. var robot = _robotService.GetRobot(item.Id);
  319. robot.ReceivedEvent += Management_ReceivedEvent;
  320. robot.SendEvent += Management_SendEvent;
  321. robot.ConnectedEvent += Management_ConnectedEvent;
  322. robot.DisconnectedEvent += Management_DisconnectedEvent;
  323. await robot.ConnectAsync(); //连接Robot
  324. SendTaskMessage($"{item.RobotName}{Lang.已连接}!", MessageLevel.Debug);
  325. }
  326. catch (Exception ex)
  327. {
  328. sb.AppendLine($"{item.RobotName}:{Lang.断开连接}![{ex.Message}]");
  329. SendTaskMessage($"{item.RobotName}{Lang.断开连接}!", MessageLevel.Alarm);
  330. }
  331. }
  332. if (sb.Length == 0)
  333. {
  334. return (true, "");
  335. }
  336. else
  337. {
  338. return (false, sb.ToString());
  339. }
  340. }
  341. /// <summary>
  342. /// 初始化扫码枪
  343. /// </summary>
  344. /// <returns></returns>
  345. public async Task<(bool IsSucceed, string Msg)> InitScanners()
  346. {
  347. var scanners = _configService.GetAllScanners();
  348. StringBuilder sb = new StringBuilder();
  349. foreach (var item in scanners)
  350. {
  351. _scannerService.CreateScanner(item.Id, item);
  352. try
  353. {
  354. Status.Add(new StatusInfo(item.Id, item.ScannerName + $"{Lang.未连接}", new SolidColorBrush(Colors.Red)));
  355. var scanner = _scannerService.GetScanner(item.Id);
  356. scanner.ReceivedEvent += Management_ScannerReceivedEvent;
  357. scanner.SendEvent += Management_ScannerSendEvent;
  358. scanner.ConnectedEvent += Management_ScannerConnectedEvent;
  359. scanner.DisconnectedEvent += Management_ScannerDisconnectedEvent;
  360. await scanner.ConnectAsync(); //连接Scanner
  361. SendTaskMessage($"{item.ScannerName}{Lang.已连接}!", MessageLevel.Debug);
  362. }
  363. catch (Exception ex)
  364. {
  365. sb.AppendLine($"{item.ScannerName}:{Lang.断开连接}![{ex.Message}]");
  366. SendTaskMessage($"{item.ScannerName}{Lang.断开连接}!", MessageLevel.Alarm);
  367. }
  368. }
  369. if (sb.Length == 0)
  370. {
  371. return (true, "");
  372. }
  373. else
  374. {
  375. return (false, sb.ToString());
  376. }
  377. }
  378. /// <summary>
  379. /// 初始化PLC
  380. /// </summary>
  381. /// <returns></returns>
  382. public async Task<(bool IsSucceed, string Msg)> InitPlc()
  383. {
  384. var plcs = _configService.GetAllPlcs();
  385. StringBuilder sb = new StringBuilder();
  386. foreach (var item in plcs)
  387. {
  388. try
  389. {
  390. _plcService.CreatePlc(item.Id, item);
  391. var plc = _plcService.GetPlc(item.Id);
  392. Status.Add(new StatusInfo(item.Id, item.Name + $"{Lang.未连接}", new SolidColorBrush(Colors.Red)));
  393. plc.ConnectChangedEvent += Management_PlcConnectChangedEvent;
  394. await plc.ConnectAsync(); //连接PLC
  395. //SendTaskMessage($"{item.Name}{Lang.已连接}!", MessageLevel.Debug);
  396. }
  397. catch (Exception ex)
  398. {
  399. sb.AppendLine($"{item.Name}:{Lang.断开连接}![{ex.Message}]");
  400. SendTaskMessage($"{item.Name}{Lang.断开连接}!", MessageLevel.Alarm);
  401. }
  402. }
  403. try
  404. {
  405. await WriteSystemParameterToPlcAsync(_configService.GetSystemConfiguration());
  406. RegisterPlcMonitorAddress();
  407. }
  408. catch (Exception ex)
  409. {
  410. LogHelper.WriteLogError("为PLC写入系统参数和订阅变量时出错", ex);
  411. }
  412. if (sb.Length == 0)
  413. {
  414. return (true, "");
  415. }
  416. else
  417. {
  418. return (false, sb.ToString());
  419. }
  420. }
  421. /// <summary>
  422. /// 初始化相机
  423. /// </summary>
  424. /// <returns></returns>
  425. public async Task<(bool IsSucceed, string Msg)> InitCameras()
  426. {
  427. var cameras = _configService.GetAllCameras();
  428. StringBuilder sb = new StringBuilder();
  429. foreach (var item in cameras)
  430. {
  431. if (item.DisplatConfigs != null)
  432. {
  433. foreach (var item1 in item.DisplatConfigs)
  434. {
  435. Renders.Add(new ShowRender() { Id = item1.Id, DisplayName = item1.DisplayName });
  436. }
  437. }
  438. _cameraService.CreateCamera(item.Id, item);
  439. try
  440. {
  441. var camera = _cameraService.GetCamera(item.Id);
  442. Status.Add(new StatusInfo(item.Id, item.CameraName + $"{Lang.未连接}", new SolidColorBrush(Colors.Red)));
  443. camera.CameraConnectChangedEvent += Management_CameraConnectChangedEvent;
  444. camera.ImageCallbackEvent += Camera_ImageCallbackEvent;
  445. try
  446. {
  447. if (await camera.OpenDeviceAsync())
  448. {
  449. SendTaskMessage($"{item.CameraName}{Lang.已连接}!", MessageLevel.Debug);
  450. }
  451. else
  452. {
  453. SendTaskMessage($"{item.CameraName}{Lang.连接失败}!", MessageLevel.Alarm);
  454. sb.AppendLine($"{item.CameraName}:{Lang.连接失败}!");
  455. }
  456. }
  457. catch (Exception ex)
  458. {
  459. SendTaskMessage($"{item.CameraName}{ex.Message}!", MessageLevel.Alarm);
  460. sb.AppendLine($"{item.CameraName}:{ex.Message}!");
  461. }
  462. }
  463. catch (Exception ex)
  464. {
  465. SendTaskMessage($"{item.CameraName}{Lang.连接失败}!", MessageLevel.Alarm);
  466. sb.AppendLine($"{item.CameraName}:{Lang.连接失败}!:{ex.Message}");
  467. }
  468. }
  469. _container.Resolve<ShowVisionRenderViewModel>().Renders = Renders;
  470. if (sb.Length == 0)
  471. {
  472. return (true, "");
  473. }
  474. else
  475. {
  476. return (false, sb.ToString());
  477. }
  478. }
  479. private void Camera_ImageCallbackEvent(ICogImage arg1, TimeSpan arg2, string arg3, Guid cameraId)
  480. {
  481. var camera = _configService.GetCamera(cameraId);
  482. SendTaskMessage($"相机[{camera.CameraName}]图像接收完成!", MessageLevel.Info);
  483. //if (camera.CameraNo == 1)
  484. //{
  485. // ImageData[1] = 1;
  486. //}
  487. //else if (camera.CameraNo == 2)
  488. //{
  489. // ImageData[2] = 1;
  490. //}
  491. //else if (camera.CameraNo == 3)
  492. //{
  493. // ImageData[3] = 1;
  494. // ImageData[4] = 1;
  495. //}
  496. //_eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
  497. //{
  498. // CameraName = camera.CameraName,
  499. // Id = cameraId,
  500. // Image = arg1,
  501. // Graphic = null,
  502. // Record = null,
  503. // Result = false,
  504. // IsShow = true,
  505. //});
  506. // 通知等待方:该相机新图到达
  507. //SignalImageArrived(cameraId, arg1);
  508. }
  509. /// <summary>
  510. /// 初始化光源控制器
  511. /// </summary>
  512. /// <returns></returns>
  513. public async Task<(bool IsSucceed, string Msg)> InitLightControllers()
  514. {
  515. var lightcontrollers = _configService.GetAllLightControllers();
  516. StringBuilder sb = new StringBuilder();
  517. foreach (var item in lightcontrollers)
  518. {
  519. try
  520. {
  521. var lishtCtr = await _lightManagerService.RegisterControllerAsync(item.Id, item);
  522. //var lightcontroller = _cameraService.GetLightController(item.Id);
  523. //await lightcontroller.ConnectAsync(); //连接光源控制器
  524. //SendTaskMessage($"{item.LightControllerName}{Lang.已连接}!", MessageLevel.Debug);
  525. }
  526. catch (Exception ex)
  527. {
  528. //sb.AppendLine($"{item.LightControllerName}:{Lang.断开连接}![{ex.Message}]");
  529. //SendTaskMessage($"{item.LightControllerName}{Lang.断开连接}!", MessageLevel.Alarm);
  530. }
  531. }
  532. if (lightcontrollers.Count > 0)
  533. {
  534. var result = await _lightManagerService.ConnectAllAsync();
  535. if (result)
  536. {
  537. return (true, "");
  538. }
  539. else
  540. {
  541. return (false, "Light Controller Connect Failed!");
  542. }
  543. }
  544. return (true, "");
  545. //if (sb.Length == 0)
  546. //{
  547. // return (true, "");
  548. //}
  549. //else
  550. //{
  551. // return (false, sb.ToString());
  552. //}
  553. }
  554. /// <summary>
  555. /// 初始化后台TCP服务器通讯
  556. /// </summary>
  557. public void InitBgTcp()
  558. {
  559. var config = _configService.GetBgTcp();
  560. try
  561. {
  562. BgCommunicate = new BgCommunicate(config);
  563. BgCommunicate.ConnectedEvent += BgCommunicate_ConnectedEvent;
  564. BgCommunicate.DisconnectedEvent += BgCommunicate_DisconnectedEvent;
  565. BgCommunicate.ReceivedEvent += BgCommunicate_ReceivedEvent;
  566. BgCommunicate.SendEvent += BgCommunicate_SendEvent;
  567. BgCommunicate.StartListening();
  568. SendTaskMessage($"{Lang.已开启监听端口}:{config.Port}", MessageLevel.Debug);
  569. }
  570. catch (Exception ex)
  571. {
  572. SendTaskMessage($"{Lang.未开启监听端口}:{config.Port}", MessageLevel.Error);
  573. LogHelper.WriteLogError("开启后台服务器通讯时出错!", ex);
  574. }
  575. }
  576. /// <summary>
  577. /// 初始化后台ModbusTCP从站
  578. /// </summary>
  579. public void InitModbusTcp()
  580. {
  581. try
  582. {
  583. var config = _configService.GetBgModbusTcp();
  584. BgModbusTcpCommunicate = new BgModbusTcpCommunicate(config);
  585. if (config.IsEnabled)
  586. {
  587. BgModbusTcpCommunicate.Listen();
  588. SendTaskMessage($"Start Modbus Tcp Slave:{BgModbusTcpCommunicate.IP}:{BgModbusTcpCommunicate.Port}:{BgModbusTcpCommunicate.SlaveID}", MessageLevel.Debug);
  589. }
  590. }
  591. catch (Exception ex)
  592. {
  593. SendTaskMessage($"No Start Modbus Tcp Slave:{ex.Message}", MessageLevel.Alarm);
  594. LogHelper.WriteLogError("开启后台Modbus TCP通讯时出错!", ex);
  595. }
  596. }
  597. /// <summary>
  598. /// 初始化后台脚本
  599. /// </summary>
  600. public void InitBackgroundcript()
  601. {
  602. try
  603. {
  604. if (!Directory.Exists(FilePath.BackgroundScriptPath))
  605. {
  606. Directory.CreateDirectory(FilePath.BackgroundScriptPath);
  607. }
  608. try
  609. {
  610. string[] files = Directory.GetFiles(FilePath.BackgroundScriptPath);
  611. List<string> ScriptFilesCollection = new List<string>();
  612. foreach (string file in files)
  613. {
  614. string fileName = Path.GetFileName(file);
  615. string fileExtension = Path.GetExtension(file);
  616. if (fileExtension == ".cs")
  617. {
  618. ScriptFilesCollection.Add(file);
  619. }
  620. }
  621. foreach (var item in ScriptFilesCollection)
  622. {
  623. try
  624. {
  625. string script = FileHelper.ReadFile(item);
  626. SendTaskMessage($"{Lang.执行脚本}:{item}", MessageLevel.Info);
  627. Task.Factory.StartNew(() =>
  628. {
  629. ScriptHelper.ExecuteScriptingAsync(script, _regionManager, _eventAggregator, _container, rst =>
  630. {
  631. if (!rst.Item1)
  632. {
  633. foreach (var err in rst.Item2)
  634. {
  635. SendTaskMessage($"{Lang.后台脚本出错}:{err}", MessageLevel.Error);
  636. }
  637. }
  638. });
  639. });
  640. }
  641. catch (Exception ex)
  642. {
  643. LogHelper.WriteLogError($"开启脚本时出错:{item}", ex);
  644. }
  645. }
  646. }
  647. catch (Exception ex)
  648. {
  649. LogHelper.WriteLogError("读取本地脚本文件列表时出错", ex);
  650. }
  651. }
  652. catch (Exception ex)
  653. {
  654. LogHelper.WriteLogError("开启后台脚本时出错!", ex);
  655. }
  656. }
  657. /// <summary>
  658. /// 初始化电批
  659. /// </summary>
  660. /// <returns></returns>
  661. public async Task InitScrewDriver()
  662. {
  663. try
  664. {
  665. var screwDriverConfig = _configService.GetScrewDriverConfig();
  666. ScrewDriver = new XYD_ScrewDriver(screwDriverConfig.IPAdress, screwDriverConfig.Port);
  667. Status.Add(new StatusInfo(ScrewDriver.Id, "电批未连接", new SolidColorBrush(Colors.Red)));
  668. ScrewDriver.ConnectStateChangedEvent += ScrewDriver_ConnectStateChangedEvent;
  669. ScrewDriver.SendTimeout = screwDriverConfig.SendTimeout;
  670. screwDriverConfig.ReceiveTimeout = screwDriverConfig.ReceiveTimeout;
  671. var isConnected = await ScrewDriver.ConnectAsync();
  672. if (isConnected)
  673. {
  674. SendTaskMessage($"电批已连接", MessageLevel.Debug);
  675. }
  676. else
  677. {
  678. SendTaskMessage($"电批连接失败", MessageLevel.Error);
  679. }
  680. }
  681. catch (Exception ex)
  682. {
  683. SendTaskMessage($"电批连接失败:{ex.Message}", MessageLevel.Alarm);
  684. LogHelper.WriteLogError("连接电批时出错!", ex);
  685. }
  686. }
  687. public async Task InitScan()
  688. {
  689. if (!File.Exists(FilePath.ScanRS232ConfigPath))
  690. {
  691. var scan = new ScanRs232ConfigModel();
  692. FileHelper.WriteJsonFile(scan, FilePath.ScanRS232ConfigPath);
  693. }
  694. try
  695. {
  696. var res = FileHelper.ReadJsonFile<ScanRs232ConfigModel>(FilePath.ScanRS232ConfigPath);
  697. if (res != null)
  698. {
  699. Scan_Client = new SerialPortClient();
  700. Scan_Client.Connecting = (client1, e) => { return EasyTask.CompletedTask; };//即将连接到端口
  701. Scan_Client.Connected = (client1, e) => { return EasyTask.CompletedTask; };//成功连接到端口
  702. Scan_Client.Closing = (client1, e) => { return EasyTask.CompletedTask; };//即将从端口断开连接。此处仅主动断开才有效。
  703. Scan_Client.Closed = (client1, e) => { return EasyTask.CompletedTask; };//从端口断开连接,当连接不成功时不会触发。
  704. Scan_Client.Received = async (c, e) =>
  705. {
  706. //await Console.Out.WriteLineAsync(Encoding.UTF8.GetString(e.ByteBlock.Buffer));
  707. await Console.Out.WriteLineAsync(e.ByteBlock.Span.ToString(Encoding.ASCII));
  708. };
  709. Scan_Client.Received = Scan_DataReceived;
  710. await Scan_Client.SetupAsync(new TouchSocketConfig()
  711. .SetSerialPortOption(new SerialPortOption()
  712. {
  713. BaudRate = res.BaudRate,//波特率
  714. DataBits = res.DataBits,//数据位
  715. Parity = res.Parity,//校验位
  716. PortName = res.PortName,//COM
  717. StopBits = res.StopBits//停止位
  718. })
  719. .SetSerialDataHandlingAdapter(() => new PeriodPackageAdapter() { CacheTimeout = TimeSpan.FromMilliseconds(100) })
  720. );
  721. await Scan_Client.ConnectAsync();
  722. if (Scan_Client.Online)
  723. {
  724. SendTaskMessage(Lang.扫码机已连接, MessageLevel.Debug);
  725. }
  726. else
  727. {
  728. SendTaskMessage(Lang.扫码机未连接, MessageLevel.Debug);
  729. }
  730. }
  731. else
  732. {
  733. SendTaskMessage(Lang.请设置扫码机串口, MessageLevel.Error);
  734. }
  735. }
  736. catch (Exception ex)
  737. {
  738. LogHelper.WriteLogError("初始化扫码枪时出错!", ex);
  739. SendTaskMessage(Lang.初始化扫码枪时出错 + ex.Message, MessageLevel.Error);
  740. }
  741. }
  742. #endregion
  743. #region 机器人指令执行
  744. public Dictionary<Guid, CancellationTokenSource> RobotTCPCollection = new Dictionary<Guid, CancellationTokenSource>();
  745. public Dictionary<Guid, CancellationTokenSource> ScannerTCPCollection = new Dictionary<Guid, CancellationTokenSource>();
  746. /// <summary>
  747. /// 机器人TCP接收
  748. /// </summary>
  749. /// <param name="arg1"></param>
  750. /// <param name="arg2"></param>
  751. /// <param name="arg3"></param>
  752. private async void Management_ReceivedEvent(Guid robotid, object arg2, TouchSocket.Sockets.ReceivedDataEventArgs e)
  753. {
  754. try
  755. {
  756. if (!RobotTCPCollection.ContainsKey(robotid))
  757. RobotTCPCollection.Add(robotid, new CancellationTokenSource());
  758. else
  759. {
  760. if (RobotTCPCollection[robotid].IsCancellationRequested)
  761. {
  762. RobotTCPCollection[robotid] = new CancellationTokenSource();
  763. }
  764. }
  765. var robot = await _robotService.GetRobotAsync(robotid);
  766. //从服务器收到信息。但是一般byteBlock和requestInfo会根据适配器呈现不同的值。
  767. var buffer = e.ByteBlock.Span.ToString(robot.GetEncoding());
  768. SendTaskMessage($"{robot.Name}Received:{buffer}", MessageLevel.Info);
  769. var _ = _remoteCommandService.ExecuteAsync(buffer, RobotTCPCollection[robotid].Token, async msg =>
  770. {
  771. try
  772. {
  773. if (robot.ConnectType == TCPConnectType.Client)
  774. {
  775. if (robot.IsConnected)
  776. {
  777. await robot.SendAsync($"{msg}");
  778. }
  779. }
  780. else
  781. {
  782. var cient = (ITcpSessionClient)arg2;
  783. if (cient.Online)
  784. {
  785. await robot.SendAsync(cient, $"{msg}");
  786. }
  787. }
  788. }
  789. catch (Exception ex)
  790. {
  791. LogHelper.WriteLogError("TCP发送数据时出错!", ex);
  792. SendTaskMessage(ex.Message, MessageLevel.Alarm);
  793. }
  794. });
  795. }
  796. catch (Exception ex)
  797. {
  798. LogHelper.WriteLogError("处理机器人接收的命令时出错!", ex);
  799. SendTaskMessage(ex.Message, MessageLevel.Alarm);
  800. }
  801. }
  802. /// <summary>
  803. /// 扫码枪TCP接收
  804. /// </summary>
  805. /// <param name="arg1"></param>
  806. /// <param name="arg2"></param>
  807. /// <param name="arg3"></param>
  808. private async void Management_ScannerReceivedEvent(Guid scannerid, object arg2, TouchSocket.Sockets.ReceivedDataEventArgs e)
  809. {
  810. try
  811. {
  812. if (!ScannerTCPCollection.ContainsKey(scannerid))
  813. ScannerTCPCollection.Add(scannerid, new CancellationTokenSource());
  814. else
  815. {
  816. if (ScannerTCPCollection[scannerid].IsCancellationRequested)
  817. {
  818. ScannerTCPCollection[scannerid] = new CancellationTokenSource();
  819. }
  820. }
  821. var scanner = await _scannerService.GetScannerAsync(scannerid);
  822. //从服务器收到信息。但是一般byteBlock和requestInfo会根据适配器呈现不同的值。
  823. var buffer = e.ByteBlock.Span.ToString(scanner.GetEncoding());
  824. var reply = (buffer ?? string.Empty).Trim();
  825. SendTaskMessage($"{scanner.Name}Received:{reply}", MessageLevel.Info);
  826. // 只要有人在等扫码结果,就先完成等待(避免被下面 ExecuteAsync 干扰)
  827. var tcs = _scanTcs;
  828. if (tcs != null && !string.IsNullOrWhiteSpace(reply))
  829. {
  830. // 只完成一次
  831. tcs.TrySetResult(reply);
  832. }
  833. var _ = _remoteCommandService.ExecuteAsync(buffer, ScannerTCPCollection[scannerid].Token, async msg =>
  834. {
  835. try
  836. {
  837. if (scanner.ConnectType == TCPConnectType.Client)
  838. {
  839. if (scanner.IsConnected)
  840. {
  841. await scanner.SendAsync($"{msg}");
  842. }
  843. }
  844. else
  845. {
  846. var cient = (ITcpSessionClient)arg2;
  847. if (cient.Online)
  848. {
  849. await scanner.SendAsync(cient, $"{msg}");
  850. }
  851. }
  852. }
  853. catch (Exception ex)
  854. {
  855. LogHelper.WriteLogError("TCP发送数据时出错!", ex);
  856. SendTaskMessage(ex.Message, MessageLevel.Alarm);
  857. }
  858. });
  859. }
  860. catch (Exception ex)
  861. {
  862. LogHelper.WriteLogError("处理扫码枪接收的命令时出错!", ex);
  863. SendTaskMessage(ex.Message, MessageLevel.Alarm);
  864. }
  865. }
  866. #endregion
  867. #region 机器人&Feeder&相机连接状态事件
  868. /// <summary>
  869. /// 机器人发送事件
  870. /// </summary>
  871. /// <param name="arg1"></param>
  872. /// <param name="arg2"></param>
  873. /// <param name="arg3"></param>
  874. /// <exception cref="NotImplementedException"></exception>
  875. private void Management_SendEvent(Guid robotid, object arg2, string arg3)
  876. {
  877. var r = _robotService.GetRobot(robotid);
  878. SendTaskMessage($"{r.Name}Send:{arg3}", MessageLevel.Info);
  879. }
  880. /// <summary>
  881. /// 扫码枪发送事件
  882. /// </summary>
  883. /// <param name="arg1"></param>
  884. /// <param name="arg2"></param>
  885. /// <param name="arg3"></param>
  886. /// <exception cref="NotImplementedException"></exception>
  887. private void Management_ScannerSendEvent(Guid scannerid, object arg2, string arg3)
  888. {
  889. var r = _scannerService.GetScanner(scannerid);
  890. SendTaskMessage($"{r.Name}Send:{arg3}", MessageLevel.Info);
  891. }
  892. /// <summary>
  893. /// 机器人断开连接时
  894. /// </summary>
  895. /// <param name="arg1"></param>
  896. /// <param name="arg2"></param>
  897. /// <param name="arg3"></param>
  898. /// <exception cref="NotImplementedException"></exception>
  899. private void Management_DisconnectedEvent(Guid robotid, object arg2, ClosedEventArgs arg3)
  900. {
  901. if (RobotTCPCollection.ContainsKey(robotid))
  902. {
  903. RobotTCPCollection[robotid].Cancel();
  904. }
  905. var r = _configService.GetRobot(robotid);
  906. if (r.ConnectType == TCPConnectType.Server)
  907. {
  908. ITcpSessionClient socketClient = arg2 as ITcpSessionClient;
  909. SendTaskMessage($"{r.RobotName}[{socketClient.Id}:{socketClient.IP}]{Lang.断开连接}!", MessageLevel.Error);
  910. var robot = _robotService.GetRobot(robotid);
  911. if (robot.TcpService.Count < 1)
  912. {
  913. var sta = Status.FirstOrDefault(s => s.ID == robotid);
  914. App.Current.Dispatcher.Invoke(new
  915. Action(() =>
  916. {
  917. sta.Message = $"{r.RobotName}{Lang.未连接}";
  918. sta.Background = new SolidColorBrush(Colors.Red);
  919. }));
  920. }
  921. }
  922. else
  923. {
  924. SendTaskMessage($"{r.RobotName}{Lang.断开连接}!", MessageLevel.Error);
  925. var sta = Status.FirstOrDefault(s => s.ID == robotid);
  926. App.Current.Dispatcher.Invoke(new
  927. Action(() =>
  928. {
  929. sta.Message = $"{r.RobotName}{Lang.断开连接}";
  930. sta.Background = new SolidColorBrush(Colors.Red);
  931. }));
  932. }
  933. }
  934. /// <summary>
  935. /// 扫码枪断开连接时
  936. /// </summary>
  937. /// <param name="arg1"></param>
  938. /// <param name="arg2"></param>
  939. /// <param name="arg3"></param>
  940. /// <exception cref="NotImplementedException"></exception>
  941. private void Management_ScannerDisconnectedEvent(Guid scannerid, object arg2, ClosedEventArgs arg3)
  942. {
  943. if (ScannerTCPCollection.ContainsKey(scannerid))
  944. {
  945. ScannerTCPCollection[scannerid].Cancel();
  946. }
  947. var r = _configService.GetScanner(scannerid);
  948. if (r.ConnectType == TCPConnectType.Server)
  949. {
  950. ITcpSessionClient socketClient = arg2 as ITcpSessionClient;
  951. SendTaskMessage($"{r.ScannerName}[{socketClient.Id}:{socketClient.IP}]{Lang.断开连接}!", MessageLevel.Error);
  952. var scanner = _scannerService.GetScanner(scannerid);
  953. if (scanner.TcpService.Count < 1)
  954. {
  955. var sta = Status.FirstOrDefault(s => s.ID == scannerid);
  956. App.Current.Dispatcher.Invoke(new
  957. Action(() =>
  958. {
  959. sta.Message = $"{r.ScannerName}{Lang.未连接}";
  960. sta.Background = new SolidColorBrush(Colors.Red);
  961. }));
  962. }
  963. }
  964. else
  965. {
  966. SendTaskMessage($"{r.ScannerName}{Lang.断开连接}!", MessageLevel.Error);
  967. var sta = Status.FirstOrDefault(s => s.ID == scannerid);
  968. App.Current.Dispatcher.Invoke(new
  969. Action(() =>
  970. {
  971. sta.Message = $"{r.ScannerName}{Lang.断开连接}";
  972. sta.Background = new SolidColorBrush(Colors.Red);
  973. }));
  974. }
  975. }
  976. /// <summary>
  977. /// 机器人连接成功时
  978. /// </summary>
  979. /// <param name="arg1"></param>
  980. /// <param name="arg2"></param>
  981. /// <param name="arg3"></param>
  982. /// <exception cref="NotImplementedException"></exception>
  983. private void Management_ConnectedEvent(Guid robotid, object arg2, ConnectedEventArgs arg3)
  984. {
  985. var r = _configService.GetRobot(robotid);
  986. if (r.ConnectType == TCPConnectType.Server)
  987. {
  988. ITcpSessionClient socketClient = arg2 as ITcpSessionClient;
  989. SendTaskMessage($"{r.RobotName}[{socketClient.Id}:{socketClient.IP}]{Lang.已连接}!", MessageLevel.Debug);
  990. var robot = _robotService.GetRobot(robotid);
  991. if (robot.TcpService.Count > 0)
  992. {
  993. var sta = Status.FirstOrDefault(s => s.ID == robotid);
  994. App.Current.Dispatcher.Invoke(new
  995. Action(() =>
  996. {
  997. sta.Message = $"{r.RobotName}{Lang.已连接}";
  998. sta.Background = new SolidColorBrush(Colors.Green);
  999. }));
  1000. }
  1001. }
  1002. else
  1003. {
  1004. SendTaskMessage($"{r.RobotName}{Lang.已连接}!", MessageLevel.Debug);
  1005. var sta = Status.FirstOrDefault(s => s.ID == robotid);
  1006. App.Current.Dispatcher.Invoke(new
  1007. Action(() =>
  1008. {
  1009. sta.Message = $"{r.RobotName}{Lang.已连接}";
  1010. sta.Background = new SolidColorBrush(Colors.Green);
  1011. }));
  1012. }
  1013. }
  1014. /// <summary>
  1015. /// 扫码枪连接成功时
  1016. /// </summary>
  1017. /// <param name="arg1"></param>
  1018. /// <param name="arg2"></param>
  1019. /// <param name="arg3"></param>
  1020. /// <exception cref="NotImplementedException"></exception>
  1021. private void Management_ScannerConnectedEvent(Guid scannerid, object arg2, ConnectedEventArgs arg3)
  1022. {
  1023. var r = _configService.GetScanner(scannerid);
  1024. if (r.ConnectType == TCPConnectType.Server)
  1025. {
  1026. ITcpSessionClient socketClient = arg2 as ITcpSessionClient;
  1027. SendTaskMessage($"{r.ScannerName}[{socketClient.Id}:{socketClient.IP}]{Lang.已连接}!", MessageLevel.Debug);
  1028. var scanner = _scannerService.GetScanner(scannerid);
  1029. if (scanner.TcpService.Count > 0)
  1030. {
  1031. var sta = Status.FirstOrDefault(s => s.ID == scannerid);
  1032. App.Current.Dispatcher.Invoke(new
  1033. Action(() =>
  1034. {
  1035. sta.Message = $"{r.ScannerName}{Lang.已连接}";
  1036. sta.Background = new SolidColorBrush(Colors.Green);
  1037. }));
  1038. }
  1039. }
  1040. else
  1041. {
  1042. SendTaskMessage($"{r.ScannerName}{Lang.已连接}!", MessageLevel.Debug);
  1043. var sta = Status.FirstOrDefault(s => s.ID == scannerid);
  1044. App.Current.Dispatcher.Invoke(new
  1045. Action(() =>
  1046. {
  1047. sta.Message = $"{r.ScannerName}{Lang.已连接}";
  1048. sta.Background = new SolidColorBrush(Colors.Green);
  1049. }));
  1050. }
  1051. }
  1052. /// <summary>
  1053. /// Feeder连接状态改变时
  1054. /// </summary>
  1055. /// <param name="sender"></param>
  1056. /// <param name="state"></param>
  1057. private void Management_FeederConnectionStatusChanged(object sender, bool state)
  1058. {
  1059. IFeeder feeder = sender as IFeeder;
  1060. var sta = Status.FirstOrDefault(s => s.ID == feeder.Id);
  1061. if (state)
  1062. {
  1063. App.Current.Dispatcher.Invoke(new
  1064. Action(() =>
  1065. {
  1066. sta.Message = $"{feeder.Name}{Lang.已连接}";
  1067. sta.Background = new SolidColorBrush(Colors.Green);
  1068. }));
  1069. SendTaskMessage($"{feeder.Name}{Lang.已连接}!", MessageLevel.Debug);
  1070. }
  1071. else
  1072. {
  1073. App.Current.Dispatcher.Invoke(new
  1074. Action(() =>
  1075. {
  1076. sta.Message = $"{feeder.Name}{Lang.未连接}";
  1077. sta.Background = new SolidColorBrush(Colors.Red);
  1078. }));
  1079. SendTaskMessage($"{feeder.Name}{Lang.断开连接}!", MessageLevel.Error);
  1080. }
  1081. }
  1082. /// <summary>
  1083. /// 相机连接或者断开时
  1084. /// </summary>
  1085. /// <param name="id"></param>
  1086. /// <param name="state"></param>
  1087. private void Management_CameraConnectChangedEvent(Guid id, bool state)
  1088. {
  1089. var sta = Status.FirstOrDefault(s => s.ID == id);
  1090. var camera = _configService.GetCamera(id);
  1091. if (sta != null && camera != null)
  1092. {
  1093. if (state)
  1094. {
  1095. App.Current.Dispatcher.Invoke(new Action(() =>
  1096. {
  1097. sta.Message = $"{camera.CameraName}{Lang.已连接}";
  1098. sta.Background = new SolidColorBrush(Colors.Green);
  1099. }));
  1100. }
  1101. else
  1102. {
  1103. App.Current.Dispatcher.Invoke(new Action(() =>
  1104. {
  1105. sta.Message = $"{camera.CameraName}{Lang.断开连接}";
  1106. sta.Background = new SolidColorBrush(Colors.Red);
  1107. }));
  1108. }
  1109. }
  1110. }
  1111. /// <summary>
  1112. /// PLC连接状态改变事件
  1113. /// </summary>
  1114. /// <param name="plc"></param>
  1115. /// <param name="isconnected"></param>
  1116. private void Management_PlcConnectChangedEvent(object sender, bool isconnected)
  1117. {
  1118. IPlc plc = sender as IPlc;
  1119. var sta = Status.FirstOrDefault(s => s.ID == plc.Id);
  1120. if (plc.IsConnected)
  1121. {
  1122. SendTaskMessage($"{plc.Name}{Lang.已连接}!", MessageLevel.Debug);
  1123. if (sta == null) return;
  1124. App.Current.Dispatcher.Invoke(new
  1125. Action(() =>
  1126. {
  1127. sta.Message = $"{plc.Name}{Lang.已连接}";
  1128. sta.Background = new SolidColorBrush(Colors.Green);
  1129. }));
  1130. }
  1131. else
  1132. {
  1133. SendTaskMessage($"{plc.Name}{Lang.断开连接}!", MessageLevel.Error);
  1134. if (sta == null) return;
  1135. App.Current.Dispatcher.Invoke(new
  1136. Action(() =>
  1137. {
  1138. sta.Message = $"{plc.Name}{Lang.未连接}";
  1139. sta.Background = new SolidColorBrush(Colors.Red);
  1140. }));
  1141. }
  1142. }
  1143. /// <summary>
  1144. /// 电批连接状态改变时
  1145. /// </summary>
  1146. /// <param name="screwDevice"></param>
  1147. /// <param name="state"></param>
  1148. private void ScrewDriver_ConnectStateChangedEvent(object screwDevice, bool state)
  1149. {
  1150. try
  1151. {
  1152. XYD_ScrewDriver screwDriver = screwDevice as XYD_ScrewDriver;
  1153. if (state)
  1154. {
  1155. SendTaskMessage($"电批{Lang.已连接}!", MessageLevel.Debug);
  1156. var sta = Status.FirstOrDefault(s => s.ID == screwDriver.Id);
  1157. App.Current.Dispatcher.Invoke(new
  1158. Action(() =>
  1159. {
  1160. sta.Message = $"电批{Lang.已连接}";
  1161. sta.Background = new SolidColorBrush(Colors.Green);
  1162. }));
  1163. }
  1164. else
  1165. {
  1166. SendTaskMessage($"电批{Lang.未连接}!", MessageLevel.Error);
  1167. var sta = Status.FirstOrDefault(s => s.ID == screwDriver.Id);
  1168. App.Current.Dispatcher.Invoke(new
  1169. Action(() =>
  1170. {
  1171. sta.Message = $"电批{Lang.未连接}";
  1172. sta.Background = new SolidColorBrush(Colors.Red);
  1173. }));
  1174. }
  1175. }
  1176. catch (Exception ex)
  1177. {
  1178. LogHelper.WriteLogError("电批连接状态改变时出错了", ex);
  1179. }
  1180. }
  1181. #endregion
  1182. #region 后台服务器通讯事件
  1183. private void BgCommunicate_SendEvent(ITcpSessionClient client, string msg)
  1184. {
  1185. SendTaskMessage($"{Lang.服务器}[{client.ServicePort}] Send To {Lang.客户端}[{client.Id}:{client.IP}]:{msg}", MessageLevel.Info);
  1186. }
  1187. public Dictionary<string, CancellationTokenSource> BgCommunicateollection = new Dictionary<string, CancellationTokenSource>();
  1188. private async void BgCommunicate_ReceivedEvent(ITcpSessionClient client, string msg)
  1189. {
  1190. try
  1191. {
  1192. if (!BgCommunicateollection.ContainsKey(client.Id))
  1193. {
  1194. BgCommunicateollection.Add(client.Id, new CancellationTokenSource());
  1195. }
  1196. SendTaskMessage($"{Lang.服务器}[{client.ServicePort}]ReceiveFor{Lang.客户端}[{client.Id}:{client.IP}]:{msg}", MessageLevel.Info);
  1197. var _ = _remoteCommandService.ExecuteAsync(msg, BgCommunicateollection[client.Id].Token, async response =>
  1198. {
  1199. try
  1200. {
  1201. if (!client.Online)
  1202. {
  1203. return;
  1204. }
  1205. await BgCommunicate.SendAsync(client, $"{response}");
  1206. }
  1207. catch (Exception ex)
  1208. {
  1209. LogHelper.WriteLogError("后台TCP发送数据时出错!", ex);
  1210. SendTaskMessage(ex.Message, MessageLevel.Alarm);
  1211. }
  1212. });
  1213. }
  1214. catch (Exception ex)
  1215. {
  1216. LogHelper.WriteLogError("处理后台服务器接收的命令时出错!", ex);
  1217. SendTaskMessage(ex.Message, MessageLevel.Alarm);
  1218. }
  1219. }
  1220. private void BgCommunicate_DisconnectedEvent(ITcpSessionClient client, ClosedEventArgs e)
  1221. {
  1222. SendTaskMessage($"{Lang.服务器}[{client.ServicePort}]{Lang.客户端}[{client.Id}:{client.IP}]{Lang.断开连接}!", MessageLevel.Alarm);
  1223. if (BgCommunicateollection.ContainsKey(client.Id))
  1224. {
  1225. BgCommunicateollection[client.Id].Cancel();
  1226. }
  1227. }
  1228. private void BgCommunicate_ConnectedEvent(ITcpSessionClient client, ConnectedEventArgs e)
  1229. {
  1230. SendTaskMessage($"{Lang.服务器}[{client.ServicePort}]{Lang.客户端}[{client.Id}:{client.IP}]{Lang.连接成功}!", MessageLevel.Debug);
  1231. }
  1232. #endregion
  1233. #region PLC
  1234. /// <summary>
  1235. /// 将系统参数写入PLC
  1236. /// </summary>
  1237. /// <param name="systemConfiguration"></param>
  1238. /// <returns></returns>
  1239. public async Task WriteSystemParameterToPlcAsync(SystemConfiguration systemConfiguration)
  1240. {
  1241. var addressConfig = _configService.GetPlcAddresses();
  1242. var plc = _plcService.GetPlcByNumber(addressConfig.PlcNo) as OpcUaClientPLC;
  1243. if (plc == null || !plc.IsConnected) return;
  1244. Dictionary<string, object> nodeValues = new Dictionary<string, object>();
  1245. nodeValues.Add(addressConfig.Out_WorkMode.Address, (Int16)systemConfiguration.WorkMode);
  1246. nodeValues.Add(addressConfig.Out_PickPointNum.Address, (Int16)systemConfiguration.PickPointNum);
  1247. nodeValues.Add(addressConfig.Out_DowmCameraNum.Address, (Int16)systemConfiguration.DowmCameraNum);
  1248. nodeValues.Add(addressConfig.Out_UpCameraPickNum.Address, (Int16)systemConfiguration.UpCameraPickNum);
  1249. nodeValues.Add(addressConfig.Out_UpCameraPutNum.Address, (Int16)systemConfiguration.UpCameraPutNum);
  1250. nodeValues.Add(addressConfig.Out_UPCameracheckNum.Address, (Int16)systemConfiguration.UPCameracheckNum);
  1251. nodeValues.Add(addressConfig.Out_FixedCameraPickNum.Address, (Int16)systemConfiguration.FixedCameraPickNum);
  1252. nodeValues.Add(addressConfig.Out_FixedCameraPutNum.Address, (Int16)systemConfiguration.FixedCameraPutNum);
  1253. nodeValues.Add(addressConfig.Out_FixedCameracheckNum.Address, (Int16)systemConfiguration.FixedCameracheckNum);
  1254. var res = await plc.WriteNodesAsync(nodeValues);
  1255. }
  1256. /// <summary>
  1257. /// 注册需要监控的PLC地址
  1258. /// </summary>
  1259. public void RegisterPlcMonitorAddress()
  1260. {
  1261. var addressConfig = _configService.GetPlcAddresses();
  1262. var plc = _plcService.GetPlcByNumber(addressConfig.PlcNo) as OpcUaClientPLC;
  1263. if (plc == null || !plc.IsConnected) return;
  1264. //PLC地址数组
  1265. List<string> monitorNodeIds = new List<string>()
  1266. {
  1267. addressConfig.In_DowmCameraExe.Address,
  1268. addressConfig.In_UpCameraPickExe.Address,
  1269. addressConfig.In_UpCameraPutExe.Address,
  1270. addressConfig.In_UPCameracheckExe.Address,
  1271. addressConfig.In_FixedCameraPickExe.Address,
  1272. addressConfig.In_FixedCameraPutExe.Address,
  1273. addressConfig.In_FixedCameracheckExe.Address,
  1274. addressConfig.In_WorkStart.Address,
  1275. addressConfig.In_WorkDone.Address,
  1276. addressConfig.In_MesCheck.Address,
  1277. addressConfig.In_RequestPosition.Address,
  1278. addressConfig.AutoRunning.Address,
  1279. addressConfig.ManualMode.Address,
  1280. addressConfig.ClearMode.Address,
  1281. };
  1282. for (int i = 0; i < 10; i++)
  1283. {
  1284. monitorNodeIds.Add(string.Format(addressConfig.In_MesCheck.Address, i));
  1285. }
  1286. //订阅PLC地址变化
  1287. plc.SubscribeNodes("AutoSensor", monitorNodeIds, PlcCommandTrigger);
  1288. }
  1289. /// <summary>
  1290. /// 写入点位信息给PLC
  1291. /// </summary>
  1292. /// <returns></returns>
  1293. public async Task WritePositionToPlcAsync()
  1294. {
  1295. var addressConfig = _configService.GetPlcAddresses();
  1296. var plc = _plcService.GetPlcByNumber(addressConfig.PlcNo) as OpcUaClientPLC;
  1297. if (plc == null || !plc.IsConnected) return;
  1298. var current = _productService.GetCurrentProduct();
  1299. if (current == null) return;
  1300. if (current.PickCameraPoints != null && current.PickCameraPoints.Count > 0)
  1301. {
  1302. foreach (var item in current.PickCameraPoints)
  1303. {
  1304. await item.WriteToPlcAddress(addressConfig.Out_PickCamera, plc);
  1305. }
  1306. }
  1307. if (current.PickPoints != null && current.PickPoints.Count > 0)
  1308. {
  1309. foreach (var item in current.PickPoints)
  1310. {
  1311. await item.WriteToPlcAddress(addressConfig.Out_Pick, plc);
  1312. }
  1313. }
  1314. if (current.SecPosCameraPoints != null && current.SecPosCameraPoints.Count > 0)
  1315. {
  1316. foreach (var item in current.SecPosCameraPoints)
  1317. {
  1318. await item.WriteToPlcAddress(addressConfig.Out_SecPosCamera, plc);
  1319. }
  1320. }
  1321. if (current.ScrewCameraPoints != null && current.ScrewCameraPoints.Count > 0)
  1322. {
  1323. foreach (var item in current.ScrewCameraPoints)
  1324. {
  1325. await item.WriteToPlcAddress(addressConfig.Out_ScrewCamera, plc);
  1326. }
  1327. }
  1328. //if (current.ScrewPoints != null && current.ScrewPoints.Count > 0)
  1329. //{
  1330. // foreach (var item in current.ScrewPoints)
  1331. // {
  1332. // await item.WriteToPlcAddress(addressConfig.Out_Screw, plc);
  1333. // }
  1334. // await plc.WriteNodeAsync(addressConfig.Out_WorkNum.Address, (Int16)current.ScrewPoints.Count);
  1335. //}
  1336. if (current.CheckCameraPoints != null && current.CheckCameraPoints.Count > 0)
  1337. {
  1338. foreach (var item in current.CheckCameraPoints)
  1339. {
  1340. await item.WriteToPlcAddress(addressConfig.Out_CheckCamera, plc);
  1341. }
  1342. }
  1343. if (current.AoiPoints != null && current.AoiPoints.Count > 0)
  1344. {
  1345. await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickNum.Address, (Int16)current.AoiPoints.Count);
  1346. foreach (var item in current.AoiPoints)
  1347. {
  1348. await item.WriteToPlcAddress(addressConfig.Out_AoiCamera, plc);
  1349. }
  1350. }
  1351. else
  1352. {
  1353. await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickNum.Address, 0);
  1354. }
  1355. }
  1356. PointF[] DowmCameraResults = new PointF[10];
  1357. PointF[] UpCameraPutResults = new PointF[10];
  1358. bool _LastDowmCameraExe = false;
  1359. bool _LastScrewTeachExe = false;
  1360. bool _LastUpCameraPickExe = false;
  1361. bool _LastUpCameraPutExe = false;
  1362. bool _LastUPCameracheckExe = false;
  1363. bool _LastFixedCameraPickExe = false;
  1364. bool _LastFixedCameraPutExe = false;
  1365. bool _LastFixedCameracheckExe = false;
  1366. public bool _LastAutoRunning = false;
  1367. public bool _LastManualMode = false;
  1368. bool _LastClearMode = false;
  1369. Int16 _LastWorkStart = 0;
  1370. Int16 _LastWorkDone = 0;
  1371. Int16 _LastRequestPosition = 0;
  1372. Int16[] _LastMesCheck = new Int16[10];
  1373. Int16 _LastPickINC = 0;
  1374. DateTime[] _LastMesCheckTime = new DateTime[10];
  1375. List<Task<(bool IsSucceed, bool[] Result, string Message)>> _PrcTaskList = new List<Task<(bool IsSucceed, bool[] Result, string Message)>>();
  1376. List<Task<(bool IsSucceed, ICogImage[] Images, string Message, int cameraIndex, Guid procedureId)>> _ImageTaskList = new List<Task<(bool IsSucceed, ICogImage[] Images, string Message, int cameraIndex, Guid procedureId)>>();
  1377. private readonly object _stateLock = new object();
  1378. /// <summary>
  1379. /// PLC命令触发时
  1380. /// </summary>
  1381. /// <param name="tuple"></param>
  1382. private async void PlcCommandTrigger((string key, string nodeId, object value) tuple)
  1383. {
  1384. try
  1385. {
  1386. if (tuple.key != "AutoSensor")
  1387. {
  1388. return;
  1389. }
  1390. var addressConfig = _configService.GetPlcAddresses();
  1391. var plc = _plcService.GetPlcByNumber(addressConfig.PlcNo) as OpcUaClientPLC;
  1392. if (plc == null || !plc.IsConnected) return;
  1393. // 获取当前产品
  1394. var currentProduct = _productService.GetCurrentProduct();
  1395. if (currentProduct == null)
  1396. {
  1397. return;
  1398. }
  1399. ////获取产品编码
  1400. //_productService.CurrentProductCode = currentProduct.Name;
  1401. //string productCode = plc.ReadNode<string>(addressConfig.In_Code.Address);
  1402. ////如果产品编码为空,则以当前的时间戳作为编码
  1403. //if (string.IsNullOrEmpty(productCode))
  1404. //{
  1405. // productCode = DateTime.Now.ToString("yyyyMMddHHmmssfff");
  1406. //}
  1407. // 写入3D相机长度
  1408. if (addressConfig.In_UPCameracheckExe.Address.Contains(tuple.nodeId))
  1409. {
  1410. if (tuple.value is bool state)
  1411. {
  1412. if (_LastUPCameracheckExe != state)
  1413. {
  1414. _LastUPCameracheckExe = state;
  1415. }
  1416. else
  1417. {
  1418. return;
  1419. }
  1420. if (state)
  1421. {
  1422. SendTaskMessage($"写入3D相机长度...", MessageLevel.Debug);
  1423. //相机的编号
  1424. //Int16 cameraIndex = plc.ReadNode<Int16>(addressConfig.In_FixedCameracheckNum.Address);
  1425. // 读取相机编号
  1426. Int16 cameraIndex = plc.ReadNode<Int16>(addressConfig.In_FixedCameracheckNum.Address);
  1427. SendTaskMessage($"编号:{cameraIndex}", MessageLevel.Info);
  1428. // 找到对应编号的 PlcPoint
  1429. var targetPoint = currentProduct.AoiPoints?.FirstOrDefault(p => p.Number == cameraIndex);
  1430. if (targetPoint == null)
  1431. {
  1432. SendTaskMessage($"未找到 AOI 点位,编号:{cameraIndex}", MessageLevel.Alarm);
  1433. await plc.WriteNodeAsync(addressConfig.Out_UPCameracheckStatus.Address, (Int16)2);
  1434. return;
  1435. }
  1436. SetProducts(new int[] { targetPoint.Camera_Product1, targetPoint.Camera_Product2, targetPoint.Camera_Product3, targetPoint.Camera_Product4 });
  1437. SetBatchPoints(new int[] { targetPoint.Camera_Data1, targetPoint.Camera_Data2, targetPoint.Camera_Data3, targetPoint.Camera_Data4 });
  1438. await plc.WriteNodeAsync(addressConfig.Out_UPCameracheckStatus.Address, (Int16)1);
  1439. }
  1440. else
  1441. {
  1442. SendTaskMessage($"写入3D相机长度信号已关闭", MessageLevel.Alarm);
  1443. await plc.WriteNodeAsync(addressConfig.Out_UPCameracheckStatus.Address, (Int16)0);
  1444. }
  1445. }
  1446. }
  1447. // 发送点位个数
  1448. else if (addressConfig.In_RequestPosition.Address.Contains(tuple.nodeId))
  1449. {
  1450. if (tuple.value is Int16 state)
  1451. {
  1452. if (_LastRequestPosition != state)
  1453. {
  1454. _LastRequestPosition = state;
  1455. }
  1456. else
  1457. {
  1458. return;
  1459. }
  1460. if (state == 1)
  1461. {
  1462. var current = _productService.GetCurrentProduct();
  1463. if (current == null) return;
  1464. await plc.WriteNodeAsync(addressConfig.Out_CameraDone.Address, (Int16)1);
  1465. await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickNum.Address, (Int16)current.AoiPoints.Count);
  1466. }
  1467. else
  1468. {
  1469. SendTaskMessage($"多相机坐标合并请求已结束或被取消,state={state}", MessageLevel.Alarm);
  1470. await plc.WriteNodeAsync(addressConfig.Out_CameraDone.Address, (Int16)0);
  1471. }
  1472. }
  1473. }
  1474. // 固定相机检测拍照
  1475. else if (addressConfig.In_FixedCameracheckExe.Address.Contains(tuple.nodeId))
  1476. {
  1477. if (tuple.value is bool state)
  1478. {
  1479. if (_LastFixedCameracheckExe != state)
  1480. {
  1481. _LastFixedCameracheckExe = state;
  1482. }
  1483. else
  1484. {
  1485. return;
  1486. }
  1487. if (state)
  1488. {
  1489. LockResult lockResult = new LockResult();
  1490. lockResult.TimeStart = DateTime.Now;
  1491. SendTaskMessage($"触发固定相机检测拍照...", MessageLevel.Debug);
  1492. // 读取相机编号
  1493. Int16 cameraIndex = plc.ReadNode<Int16>(addressConfig.In_FixedCameracheckNum.Address);
  1494. SendTaskMessage($"编号:{cameraIndex}", MessageLevel.Info);
  1495. // 找到对应编号的 PlcPoint
  1496. var targetPoint = currentProduct.AoiPoints?.FirstOrDefault(p => p.Number == cameraIndex);
  1497. if (targetPoint == null)
  1498. {
  1499. SendTaskMessage($"未找到 AOI 点位,编号:{cameraIndex}", MessageLevel.Alarm);
  1500. await plc.WriteNodeAsync(addressConfig.Out_FixedCameracheckStatus.Address, (Int16)2);
  1501. return;
  1502. }
  1503. // 收集要执行的流程 id(仅添加大于0的)
  1504. var procIds = new List<Guid>();
  1505. try
  1506. {
  1507. if (targetPoint.CameraProcedureId1 != Guid.Empty && !procIds.Contains(targetPoint.CameraProcedureId1)) procIds.Add(targetPoint.CameraProcedureId1);
  1508. }
  1509. catch { }
  1510. try
  1511. {
  1512. if (targetPoint.CameraProcedureId2 != Guid.Empty && !procIds.Contains(targetPoint.CameraProcedureId2)) procIds.Add(targetPoint.CameraProcedureId2);
  1513. }
  1514. catch { }
  1515. try
  1516. {
  1517. if (targetPoint.CameraProcedureId3 != Guid.Empty && !procIds.Contains(targetPoint.CameraProcedureId3)) procIds.Add(targetPoint.CameraProcedureId3);
  1518. }
  1519. catch { }
  1520. try
  1521. {
  1522. if (targetPoint.CameraProcedureId4 != Guid.Empty && !procIds.Contains(targetPoint.CameraProcedureId4)) procIds.Add(targetPoint.CameraProcedureId4);
  1523. }
  1524. catch { }
  1525. try
  1526. {
  1527. if (targetPoint.CameraProcedureId5 != Guid.Empty && !procIds.Contains(targetPoint.CameraProcedureId5)) procIds.Add(targetPoint.CameraProcedureId5);
  1528. }
  1529. catch { }
  1530. try
  1531. {
  1532. if (targetPoint.CameraProcedureId6 != Guid.Empty && !procIds.Contains(targetPoint.CameraProcedureId6)) procIds.Add(targetPoint.CameraProcedureId6);
  1533. }
  1534. catch { }
  1535. try
  1536. {
  1537. if (targetPoint.CameraProcedureId7 != Guid.Empty && !procIds.Contains(targetPoint.CameraProcedureId7)) procIds.Add(targetPoint.CameraProcedureId7);
  1538. }
  1539. catch { }
  1540. try
  1541. {
  1542. if (targetPoint.CameraProcedureId8 != Guid.Empty && !procIds.Contains(targetPoint.CameraProcedureId8)) procIds.Add(targetPoint.CameraProcedureId8);
  1543. }
  1544. catch { }
  1545. var sysConfig = _configService.GetSystemConfiguration();
  1546. if (sysConfig.ScannerUse == true && cameraIndex == 1 && sysConfig.CodeUse2 == true)
  1547. {
  1548. ScanValue = "";
  1549. _scanDoneEvent.Reset(); // 重要:先关门
  1550. await Scan_Client.SendAsync("T\r\n");
  1551. // 等待扫码结果,最多 3 秒
  1552. bool scanOk = await Task.Run(() => _scanDoneEvent.Wait(3000));
  1553. if (!scanOk || ScanValue.IsNullOrWhiteSpace())
  1554. {
  1555. SendTaskMessage("二维码拍照失败或超时", MessageLevel.Alarm);
  1556. await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (short)3);
  1557. return;
  1558. }
  1559. code = ScanValue;
  1560. SendTaskMessage($"扫码成功,SN:{code}", MessageLevel.Info);
  1561. //这里缺少从MES获取产品配方的内容,需要补充
  1562. _LastMesCheckTime[0] = (await _mesService.GetServerTimeAsync(code, 2)).Now;
  1563. //_LastMesCheckTime[1] = DateTime.Now;
  1564. LogHelper.WriteLogMes($"【mes开始QUERY】");
  1565. SendTaskMessage($"mes开始QUERY", MessageLevel.Info);
  1566. (bool isSuccess, string response) = await _mesService.StationGetAsync(code, "", 2);//询问mes
  1567. if (isSuccess)
  1568. {
  1569. //产品发生改变并且供料器发生了变化时,需要通知PLC进行取料更改
  1570. LogHelper.WriteLogMes($"询问mes成功");
  1571. SendTaskMessage($"询问mes成功:{response}", MessageLevel.Debug);
  1572. if (response != "MES功能未启用!")
  1573. {
  1574. string[] items = response.Split('\n');
  1575. string snItem = items.FirstOrDefault(f => f.Contains("sn="));
  1576. if (snItem != null)
  1577. {
  1578. ProductMainSN = snItem.Replace("sn=", "").Trim();
  1579. _productService.CurrentProductCode = ProductMainSN;
  1580. SendTaskMessage($"产品主sn:{ProductMainSN}", MessageLevel.Info);
  1581. }
  1582. string woItem = items.FirstOrDefault(f => f.Contains("wo="));
  1583. if (woItem != null)
  1584. {
  1585. wo = woItem.Replace("wo=", "").Trim();
  1586. SendTaskMessage($"产品wo:{wo}", MessageLevel.Info);
  1587. }
  1588. string modelItem = items.FirstOrDefault(f => f.Contains("model_num="));
  1589. if (modelItem != null)
  1590. {
  1591. model_num = modelItem.Replace("model_num=", "").Trim();
  1592. SendTaskMessage($"model_num:{model_num}", MessageLevel.Info);
  1593. }
  1594. string colorItem = items.FirstOrDefault(f => f.Contains("color="));
  1595. if (colorItem != null)
  1596. {
  1597. color = colorItem.Replace("color=", "").Trim();
  1598. SendTaskMessage($"color:{color}", MessageLevel.Info);
  1599. }
  1600. string ppidItem = items.FirstOrDefault(f => f.Contains("ppid="));
  1601. if (ppidItem != null)
  1602. {
  1603. ppid = ppidItem.Replace("ppid=", "").Trim();
  1604. SendTaskMessage($"ppid:{ppid}", MessageLevel.Info);
  1605. }
  1606. string stageItem = items.FirstOrDefault(f => f.Contains("stage="));
  1607. if (stageItem != null)
  1608. {
  1609. stage = stageItem.Replace("stage=", "").Trim();
  1610. SendTaskMessage($"stage:{revision}", MessageLevel.Info);
  1611. }
  1612. }
  1613. LogHelper.WriteLogMes($"【mes结束QUERY】");
  1614. SendTaskMessage($"mes结束QUERY", MessageLevel.Info);
  1615. var q = await _systemDatabaseService.QueryProductFromMesAsync(model_num, color);
  1616. if (!string.IsNullOrEmpty(q))
  1617. {
  1618. ProductList = new ObservableCollection<ProductModel>(_productService.GetAllProducts());
  1619. Guid productId = Guid.Empty;
  1620. foreach (var itt in ProductList)
  1621. {
  1622. if (itt.Name == q)
  1623. {
  1624. productId = itt.ID;
  1625. break;
  1626. }
  1627. }
  1628. if (currentProduct.ID != productId)
  1629. {
  1630. //切换产品
  1631. _productService.LoadProduct(productId);
  1632. _productService.SetCurrentProduct(productId);
  1633. await WritePositionToPlcAsync();
  1634. SendTaskMessage($"切换产品成功", MessageLevel.Debug);
  1635. }
  1636. }
  1637. await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)1);
  1638. return;
  1639. }
  1640. else
  1641. {
  1642. //产品发生改变并且供料器发生了变化时,需要通知PLC进行取料更改
  1643. await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)3);
  1644. LogHelper.WriteLogMes($"询问mes失败");
  1645. SendTaskMessage($"询问mes失败:{response}", MessageLevel.Error);
  1646. return;
  1647. }
  1648. }
  1649. if (sysConfig.ScannerUse == true && cameraIndex == 1 && sysConfig.CodeUse == true)
  1650. {
  1651. ScanValue = "";
  1652. _scanDoneEvent.Reset(); // 重要:先关门
  1653. await Scan_Client.SendAsync("T\r\n");
  1654. // 等待扫码结果,最多 3 秒
  1655. bool scanOk = await Task.Run(() => _scanDoneEvent.Wait(3000));
  1656. if (!scanOk || ScanValue.IsNullOrWhiteSpace())
  1657. {
  1658. SendTaskMessage("二维码拍照失败或超时", MessageLevel.Alarm);
  1659. await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (short)3);
  1660. return;
  1661. }
  1662. code = ScanValue;
  1663. SendTaskMessage($"扫码成功,SN:{code}", MessageLevel.Info);
  1664. //这里缺少从MES获取产品配方的内容,需要补充
  1665. _LastMesCheckTime[0] = (await _mesService.GetServerTimeAsync(code, 2)).Now;
  1666. LogHelper.WriteLogMes($"【mes开始QUERY】");
  1667. SendTaskMessage($"mes开始QUERY", MessageLevel.Info);
  1668. //(bool isSuccess, string response) = await _mesService.StationGetAsync(code, "", 2);//询问mes
  1669. (bool isSuccess, string response) = await _mesService.StationGetExAsync(code, "", 2);//基于电池的SN获取产品SN,询问mes
  1670. if (isSuccess)
  1671. {
  1672. //产品发生改变并且供料器发生了变化时,需要通知PLC进行取料更改
  1673. string ProductMainSN_Temp = "";
  1674. LogHelper.WriteLogMes($"询问mes成功");
  1675. SendTaskMessage($"询问mes成功:{response}", MessageLevel.Debug);
  1676. if (response != "MES功能未启用!")
  1677. {
  1678. string[] item = response.Split('\n');
  1679. string snItem = item.FirstOrDefault(f => f.Contains("sn="));
  1680. if (snItem != null)
  1681. {
  1682. ProductMainSN_Temp = snItem.Replace("sn=", "").Trim();
  1683. SendTaskMessage($"sn:{ProductMainSN_Temp}", MessageLevel.Info);
  1684. }
  1685. }
  1686. LogHelper.WriteLogMes($"询问mes成功");
  1687. SendTaskMessage($"询问mes成功:{response}", MessageLevel.Debug);
  1688. //20260214,特别版(电池组装)
  1689. (bool isSuccess2, string response2) = await _mesService.StationGetAsync(ProductMainSN_Temp, "", 2);//询问mes
  1690. if (isSuccess2)
  1691. {
  1692. LogHelper.WriteLogMes($"询问mes成功");
  1693. SendTaskMessage($"询问mes成功:{response2}", MessageLevel.Debug);
  1694. if (response2 != "MES功能未启用!")
  1695. {
  1696. string[] item = response2.Split('\n');
  1697. string snItem = item.FirstOrDefault(f => f.Contains("sn="));
  1698. if (snItem != null)
  1699. {
  1700. ProductMainSN = snItem.Replace("sn=", "").Trim();
  1701. _productService.CurrentProductCode = ProductMainSN;
  1702. SendTaskMessage($"产品主sn:{ProductMainSN}", MessageLevel.Info);
  1703. }
  1704. string woItem = item.FirstOrDefault(f => f.Contains("wo="));
  1705. if (woItem != null)
  1706. {
  1707. wo = woItem.Replace("wo=", "").Trim();
  1708. SendTaskMessage($"产品wo:{wo}", MessageLevel.Info);
  1709. }
  1710. string modelItem = item.FirstOrDefault(f => f.Contains("model_num="));
  1711. if (modelItem != null)
  1712. {
  1713. model_num = modelItem.Replace("model_num=", "").Trim();
  1714. SendTaskMessage($"model_num:{model_num}", MessageLevel.Info);
  1715. }
  1716. string colorItem = item.FirstOrDefault(f => f.Contains("color="));
  1717. if (colorItem != null)
  1718. {
  1719. color = colorItem.Replace("color=", "").Trim();
  1720. SendTaskMessage($"color:{color}", MessageLevel.Info);
  1721. }
  1722. string ppidItem = item.FirstOrDefault(f => f.Contains("ppid="));
  1723. if (ppidItem != null)
  1724. {
  1725. ppid = ppidItem.Replace("ppid=", "").Trim();
  1726. SendTaskMessage($"ppid:{ppid}", MessageLevel.Info);
  1727. }
  1728. string stageItem = item.FirstOrDefault(f => f.Contains("stage="));
  1729. if (stageItem != null)
  1730. {
  1731. stage = stageItem.Replace("stage=", "").Trim();
  1732. SendTaskMessage($"stage:{revision}", MessageLevel.Info);
  1733. }
  1734. }
  1735. LogHelper.WriteLogMes($"第二次询问mes成功");
  1736. SendTaskMessage($"第二次询问mes成功:{response2}", MessageLevel.Debug);
  1737. var q = await _systemDatabaseService.QueryProductFromMesAsync(model_num, color);
  1738. if (!string.IsNullOrEmpty(q))
  1739. {
  1740. ProductList = new ObservableCollection<ProductModel>(_productService.GetAllProducts());
  1741. Guid productId = Guid.Empty;
  1742. foreach (var itt in ProductList)
  1743. {
  1744. if (itt.Name == q)
  1745. {
  1746. productId = itt.ID;
  1747. break;
  1748. }
  1749. }
  1750. if (currentProduct.ID != productId)
  1751. {
  1752. //切换产品
  1753. _productService.LoadProduct(productId);
  1754. _productService.SetCurrentProduct(productId);
  1755. await WritePositionToPlcAsync();
  1756. SendTaskMessage($"切换产品成功", MessageLevel.Debug);
  1757. }
  1758. }
  1759. await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)1);
  1760. }
  1761. else
  1762. {
  1763. LogHelper.WriteLogMes($"第二次询问mes失败");
  1764. SendTaskMessage($"第二次询问mes失败:{response2}", MessageLevel.Error);
  1765. await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)3);
  1766. }
  1767. }
  1768. else
  1769. {
  1770. //产品发生改变并且供料器发生了变化时,需要通知PLC进行取料更改
  1771. await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)3);
  1772. LogHelper.WriteLogMes($"询问mes失败");
  1773. SendTaskMessage($"询问mes失败:{response}", MessageLevel.Error);
  1774. }
  1775. return;
  1776. }
  1777. if (procIds.Count == 0 && cameraIndex != currentProduct.PhotoCountStop)
  1778. {
  1779. SendTaskMessage($"Point#{cameraIndex} 未配置任何视觉流程 (CameraProcedureId1/2/3)", MessageLevel.Alarm);
  1780. await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)2);
  1781. return;
  1782. }
  1783. var cameraProcedures = currentProduct.CameraProcedures;
  1784. if (cameraProcedures == null || cameraProcedures.Count == 0)
  1785. {
  1786. if(cameraIndex != currentProduct.PhotoCountStop)
  1787. {
  1788. SendTaskMessage($"当前产品未配置 CameraProcedures,无法执行视觉流程", MessageLevel.Alarm);
  1789. await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)2);
  1790. return;
  1791. }
  1792. }
  1793. if (cameraIndex == currentProduct.PhotoCount)
  1794. {
  1795. _PrcTaskList.Clear();
  1796. lock (_stateLock)
  1797. {
  1798. lockResultsAll.Clear();
  1799. }
  1800. App.Current.Dispatcher.Invoke(() =>
  1801. {
  1802. _eventAggregator.GetEvent<LockResetNotification>().Publish();
  1803. });
  1804. }
  1805. if (sysConfig.CodeUse == true && cameraIndex == 1)
  1806. {
  1807. var cts = new CancellationTokenSource();
  1808. // CameraProcedureId 存储的是具体的视觉流程 Id(ProcedureModel.Id),
  1809. // 需要在所有 CameraProcedures 的 ProcedureModels 中查找匹配的流程。
  1810. ProcedureModel selectedProcedure = null;
  1811. try
  1812. {
  1813. cameraProcedures = currentProduct.CameraProcedures;
  1814. if (cameraProcedures != null)
  1815. {
  1816. foreach (var cp in cameraProcedures)
  1817. {
  1818. if (cp?.ProcedureModels == null) continue;
  1819. selectedProcedure = cp.ProcedureModels.FirstOrDefault(pm => pm.Id == targetPoint.CameraProcedureId1);
  1820. if (selectedProcedure != null) break;
  1821. }
  1822. }
  1823. }
  1824. catch (Exception ex)
  1825. {
  1826. LogHelper.WriteLogError("查找 AOI 点位对应视觉流程时出错", ex);
  1827. }
  1828. if (selectedProcedure == null)
  1829. {
  1830. SendTaskMessage($"未找到 AOI 点位对应的视觉流程,Point#{cameraIndex} ProcedureId={targetPoint.CameraProcedureId1}", MessageLevel.Alarm);
  1831. await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)2);
  1832. return;
  1833. }
  1834. if (selectedProcedure.Id == currentProduct.FixedDownCameraProcedureId && sysConfig.TurnOnAllLightUse == true)
  1835. {
  1836. await _remoteCommandService.SetLightBeforePhoto(selectedProcedure);
  1837. }
  1838. var visionResult = await _remoteCommandService.ExecutePhotoGetSinglePoint2(selectedProcedure, null, null, cts.Token);
  1839. if (visionResult.IsSucceed)
  1840. {
  1841. code = visionResult.X.ToUpper();
  1842. SendTaskMessage($"扫码成功,SN:{code}", MessageLevel.Info);
  1843. //这里缺少从MES获取产品配方的内容,需要补充
  1844. _LastMesCheckTime[0] = (await _mesService.GetServerTimeAsync(code, 2)).Now;
  1845. LogHelper.WriteLogMes($"【mes开始QUERY】");
  1846. SendTaskMessage($"mes开始QUERY", MessageLevel.Info);
  1847. //(bool isSuccess, string response) = await _mesService.StationGetAsync(code, "", 2);//询问mes
  1848. (bool isSuccess, string response) = await _mesService.StationGetExAsync(code, "", 2);//基于电池的SN获取产品SN,询问mes
  1849. if (isSuccess)
  1850. {
  1851. //产品发生改变并且供料器发生了变化时,需要通知PLC进行取料更改
  1852. string ProductMainSN_Temp = "";
  1853. LogHelper.WriteLogMes($"询问mes成功");
  1854. SendTaskMessage($"询问mes成功:{response}", MessageLevel.Debug);
  1855. if (response != "MES功能未启用!")
  1856. {
  1857. string[] item = response.Split('\n');
  1858. string snItem = item.FirstOrDefault(f => f.Contains("sn="));
  1859. if (snItem != null)
  1860. {
  1861. ProductMainSN_Temp = snItem.Replace("sn=", "").Trim();
  1862. SendTaskMessage($"sn:{ProductMainSN_Temp}", MessageLevel.Info);
  1863. }
  1864. }
  1865. LogHelper.WriteLogMes($"询问mes成功");
  1866. SendTaskMessage($"询问mes成功:{response}", MessageLevel.Debug);
  1867. //20260214,特别版(电池组装)
  1868. (bool isSuccess2, string response2) = await _mesService.StationGetAsync(ProductMainSN_Temp, "", 2);//询问mes
  1869. if (isSuccess2)
  1870. {
  1871. LogHelper.WriteLogMes($"询问mes成功");
  1872. SendTaskMessage($"询问mes成功:{response2}", MessageLevel.Debug);
  1873. if (response2 != "MES功能未启用!")
  1874. {
  1875. string[] item = response2.Split('\n');
  1876. string snItem = item.FirstOrDefault(f => f.Contains("sn="));
  1877. if (snItem != null)
  1878. {
  1879. ProductMainSN = snItem.Replace("sn=", "").Trim();
  1880. _productService.CurrentProductCode = ProductMainSN;
  1881. SendTaskMessage($"产品主sn:{ProductMainSN}", MessageLevel.Info);
  1882. }
  1883. string woItem = item.FirstOrDefault(f => f.Contains("wo="));
  1884. if (woItem != null)
  1885. {
  1886. wo = woItem.Replace("wo=", "").Trim();
  1887. SendTaskMessage($"产品wo:{wo}", MessageLevel.Info);
  1888. }
  1889. string modelItem = item.FirstOrDefault(f => f.Contains("model_num="));
  1890. if (modelItem != null)
  1891. {
  1892. model_num = modelItem.Replace("model_num=", "").Trim();
  1893. SendTaskMessage($"model_num:{model_num}", MessageLevel.Info);
  1894. }
  1895. string colorItem = item.FirstOrDefault(f => f.Contains("color="));
  1896. if (colorItem != null)
  1897. {
  1898. color = colorItem.Replace("color=", "").Trim();
  1899. SendTaskMessage($"color:{color}", MessageLevel.Info);
  1900. }
  1901. string ppidItem = item.FirstOrDefault(f => f.Contains("ppid="));
  1902. if (ppidItem != null)
  1903. {
  1904. ppid = ppidItem.Replace("ppid=", "").Trim();
  1905. SendTaskMessage($"ppid:{ppid}", MessageLevel.Info);
  1906. }
  1907. string stageItem = item.FirstOrDefault(f => f.Contains("stage="));
  1908. if (stageItem != null)
  1909. {
  1910. stage = stageItem.Replace("stage=", "").Trim();
  1911. SendTaskMessage($"stage:{revision}", MessageLevel.Info);
  1912. }
  1913. }
  1914. LogHelper.WriteLogMes($"第二次询问mes成功");
  1915. SendTaskMessage($"第二次询问mes成功:{response2}", MessageLevel.Debug);
  1916. var q = await _systemDatabaseService.QueryProductFromMesAsync(model_num, color);
  1917. if (!string.IsNullOrEmpty(q))
  1918. {
  1919. ProductList = new ObservableCollection<ProductModel>(_productService.GetAllProducts());
  1920. Guid productId = Guid.Empty;
  1921. foreach (var itt in ProductList)
  1922. {
  1923. if (itt.Name == q)
  1924. {
  1925. productId = itt.ID;
  1926. break;
  1927. }
  1928. }
  1929. if (currentProduct.ID != productId)
  1930. {
  1931. //切换产品
  1932. _productService.LoadProduct(productId);
  1933. _productService.SetCurrentProduct(productId);
  1934. await WritePositionToPlcAsync();
  1935. SendTaskMessage($"切换产品成功", MessageLevel.Debug);
  1936. }
  1937. }
  1938. await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)1);
  1939. }
  1940. else
  1941. {
  1942. LogHelper.WriteLogMes($"第二次询问mes失败");
  1943. SendTaskMessage($"第二次询问mes失败:{response2}", MessageLevel.Error);
  1944. await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)3);
  1945. }
  1946. }
  1947. else
  1948. {
  1949. //产品发生改变并且供料器发生了变化时,需要通知PLC进行取料更改
  1950. await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)3);
  1951. LogHelper.WriteLogMes($"询问mes失败");
  1952. SendTaskMessage($"询问mes失败:{response}", MessageLevel.Error);
  1953. }
  1954. }
  1955. else
  1956. {
  1957. SendTaskMessage($"扫码失败", MessageLevel.Alarm);
  1958. await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)3);
  1959. }
  1960. return;
  1961. }
  1962. if (sysConfig.CodeUse2 == true && cameraIndex == 1)
  1963. {
  1964. var cts = new CancellationTokenSource();
  1965. // CameraProcedureId 存储的是具体的视觉流程 Id(ProcedureModel.Id),
  1966. // 需要在所有 CameraProcedures 的 ProcedureModels 中查找匹配的流程。
  1967. ProcedureModel selectedProcedure = null;
  1968. try
  1969. {
  1970. cameraProcedures = currentProduct.CameraProcedures;
  1971. if (cameraProcedures != null)
  1972. {
  1973. foreach (var cp in cameraProcedures)
  1974. {
  1975. if (cp?.ProcedureModels == null) continue;
  1976. selectedProcedure = cp.ProcedureModels.FirstOrDefault(pm => pm.Id == targetPoint.CameraProcedureId1);
  1977. if (selectedProcedure != null) break;
  1978. }
  1979. }
  1980. }
  1981. catch (Exception ex)
  1982. {
  1983. LogHelper.WriteLogError("查找 AOI 点位对应视觉流程时出错", ex);
  1984. }
  1985. if (selectedProcedure == null)
  1986. {
  1987. SendTaskMessage($"未找到 AOI 点位对应的视觉流程,Point#{cameraIndex} ProcedureId={targetPoint.CameraProcedureId1}", MessageLevel.Alarm);
  1988. await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)2);
  1989. return;
  1990. }
  1991. var ctsAll = new CancellationTokenSource();
  1992. if (selectedProcedure.Id == currentProduct.FixedDownCameraProcedureId && sysConfig.TurnOnAllLightUse == true)
  1993. {
  1994. await _remoteCommandService.SetLightBeforePhoto(selectedProcedure);
  1995. }
  1996. var visionResult = await _remoteCommandService.ExecutePhotoGetSinglePoint2(selectedProcedure, null, null, ctsAll.Token);
  1997. if (visionResult.IsSucceed)
  1998. {
  1999. code = visionResult.X;
  2000. ProductMainSN = visionResult.X;
  2001. SendTaskMessage($"扫码成功,SN:{code}", MessageLevel.Info);
  2002. //这里缺少从MES获取产品配方的内容,需要补充
  2003. _LastMesCheckTime[0] = (await _mesService.GetServerTimeAsync(code, 2)).Now;
  2004. //_LastMesCheckTime[1] = DateTime.Now;
  2005. LogHelper.WriteLogMes($"【mes开始QUERY】");
  2006. SendTaskMessage($"mes开始QUERY", MessageLevel.Info);
  2007. (bool isSuccess, string response) = await _mesService.StationGetAsync(code, "", 2);//询问mes
  2008. if (isSuccess)
  2009. {
  2010. //产品发生改变并且供料器发生了变化时,需要通知PLC进行取料更改
  2011. LogHelper.WriteLogMes($"询问mes成功");
  2012. SendTaskMessage($"询问mes成功:{response}", MessageLevel.Debug);
  2013. if (response != "MES功能未启用!")
  2014. {
  2015. string[] items = response.Split('\n');
  2016. string snItem = items.FirstOrDefault(f => f.Contains("sn="));
  2017. if (snItem != null)
  2018. {
  2019. ProductMainSN = snItem.Replace("sn=", "").Trim();
  2020. _productService.CurrentProductCode = ProductMainSN;
  2021. SendTaskMessage($"产品主sn:{ProductMainSN}", MessageLevel.Info);
  2022. }
  2023. string woItem = items.FirstOrDefault(f => f.Contains("wo="));
  2024. if (woItem != null)
  2025. {
  2026. wo = woItem.Replace("wo=", "").Trim();
  2027. SendTaskMessage($"产品wo:{wo}", MessageLevel.Info);
  2028. }
  2029. string modelItem = items.FirstOrDefault(f => f.Contains("model_num="));
  2030. if (modelItem != null)
  2031. {
  2032. model_num = modelItem.Replace("model_num=", "").Trim();
  2033. SendTaskMessage($"model_num:{model_num}", MessageLevel.Info);
  2034. }
  2035. string colorItem = items.FirstOrDefault(f => f.Contains("color="));
  2036. if (colorItem != null)
  2037. {
  2038. color = colorItem.Replace("color=", "").Trim();
  2039. SendTaskMessage($"color:{color}", MessageLevel.Info);
  2040. }
  2041. string ppidItem = items.FirstOrDefault(f => f.Contains("ppid="));
  2042. if (ppidItem != null)
  2043. {
  2044. ppid = ppidItem.Replace("ppid=", "").Trim();
  2045. SendTaskMessage($"ppid:{ppid}", MessageLevel.Info);
  2046. }
  2047. string stageItem = items.FirstOrDefault(f => f.Contains("stage="));
  2048. if (stageItem != null)
  2049. {
  2050. stage = stageItem.Replace("stage=", "").Trim();
  2051. SendTaskMessage($"stage:{revision}", MessageLevel.Info);
  2052. }
  2053. }
  2054. LogHelper.WriteLogMes($"【mes结束QUERY】");
  2055. SendTaskMessage($"mes结束QUERY", MessageLevel.Info);
  2056. var q = await _systemDatabaseService.QueryProductFromMesAsync(model_num, color);
  2057. if (!string.IsNullOrEmpty(q))
  2058. {
  2059. ProductList = new ObservableCollection<ProductModel>(_productService.GetAllProducts());
  2060. Guid productId = Guid.Empty;
  2061. foreach (var itt in ProductList)
  2062. {
  2063. if (itt.Name == q)
  2064. {
  2065. productId = itt.ID;
  2066. break;
  2067. }
  2068. }
  2069. if (currentProduct.ID != productId)
  2070. {
  2071. //切换产品
  2072. _productService.LoadProduct(productId);
  2073. _productService.SetCurrentProduct(productId);
  2074. await WritePositionToPlcAsync();
  2075. SendTaskMessage($"切换产品成功", MessageLevel.Debug);
  2076. }
  2077. }
  2078. await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)1);
  2079. return;
  2080. }
  2081. else
  2082. {
  2083. //产品发生改变并且供料器发生了变化时,需要通知PLC进行取料更改
  2084. await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)3);
  2085. LogHelper.WriteLogMes($"询问mes失败");
  2086. SendTaskMessage($"询问mes失败:{response}", MessageLevel.Error);
  2087. }
  2088. }
  2089. else
  2090. {
  2091. SendTaskMessage($"扫码失败", MessageLevel.Alarm);
  2092. await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)3);
  2093. }
  2094. return;
  2095. }
  2096. _ImageTaskList.Clear();
  2097. foreach (var prcId in procIds)
  2098. {
  2099. ProcedureModel selectedProcedure = null;
  2100. try
  2101. {
  2102. foreach (var cp in cameraProcedures)
  2103. {
  2104. if (cp?.ProcedureModels == null) continue;
  2105. selectedProcedure = cp.ProcedureModels.FirstOrDefault(pm => pm.Id == prcId);
  2106. if (selectedProcedure != null) break;
  2107. }
  2108. }
  2109. catch (Exception ex)
  2110. {
  2111. LogHelper.WriteLogError("查找 AOI 点位对应视觉流程时出错", ex);
  2112. }
  2113. if (sysConfig.TurnOnAllLightUse == false)
  2114. {
  2115. await _remoteCommandService.SetLightBeforePhoto(selectedProcedure);
  2116. }
  2117. if(sysConfig.PhotosUse==true)
  2118. {
  2119. bool Is3dPhoto = Is3D(prcId);
  2120. var tt=await GrabImageEx(cameraIndex, prcId, Is3dPhoto);
  2121. if(tt.IsSucceed==false)
  2122. {
  2123. SendTaskMessage($"图像采集失败!{cameraIndex}: {prcId}", MessageLevel.Alarm);
  2124. return;
  2125. }
  2126. await ExecuteProcedureAsync(cameraIndex, prcId, tt.imges, Is3dPhoto);
  2127. }
  2128. else
  2129. {
  2130. bool Is3dPhoto = Is3D(prcId);
  2131. _ImageTaskList.Add(GrabImageEx(cameraIndex, prcId, Is3dPhoto));
  2132. }
  2133. if (sysConfig.TurnOnAllLightUse == false)
  2134. {
  2135. await _remoteCommandService.TurnOffLightAfterPhoto(selectedProcedure);
  2136. }
  2137. }
  2138. if (cameraIndex != currentProduct.PhotoCountStop)
  2139. {
  2140. //直接放行,执行下一个检测点
  2141. await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)1);
  2142. }
  2143. if (_ImageTaskList.Count > 0)//如果2D取图有队列
  2144. {
  2145. var ImageTaskResults = await Task.WhenAll(_ImageTaskList);
  2146. foreach (var item in ImageTaskResults)
  2147. {
  2148. if (item.IsSucceed)
  2149. {
  2150. bool Is3d = Is3D(item.procedureId);
  2151. _PrcTaskList.Add(ExecuteProcedureAsync(item.cameraIndex, item.procedureId, item.Images, Is3d));
  2152. //_PrcTaskList.Add(ExecuteProcedureAsync(cameraIndex, prcId, imageData.imges));
  2153. }
  2154. else
  2155. {
  2156. SendTaskMessage($"图像采集失败!{item.cameraIndex}: {item.procedureId}", MessageLevel.Alarm);
  2157. }
  2158. }
  2159. }
  2160. //如果最后一个拍照点,则需要等待前面所有的拍照处理完成
  2161. if (cameraIndex == currentProduct.PhotoCountStop)
  2162. {
  2163. //结果输出
  2164. bool resultFlog = true;
  2165. if (sysConfig.PhotosUse == true)
  2166. {
  2167. foreach (var item in lockResultsAll)
  2168. {
  2169. if (item.PhotoPassed=="NG")
  2170. {
  2171. resultFlog = false;
  2172. break;
  2173. }
  2174. }
  2175. }
  2176. else
  2177. {
  2178. //等待所有的图像处理流程处理完成
  2179. var results = await Task.WhenAll(_PrcTaskList);
  2180. foreach (var item in results)
  2181. {
  2182. if (!item.IsSucceed || item.Result == null)
  2183. {
  2184. resultFlog = false;
  2185. break;
  2186. }
  2187. else
  2188. {
  2189. foreach (var item_1 in item.Result)
  2190. {
  2191. if (!item_1)
  2192. {
  2193. resultFlog = false;
  2194. break;
  2195. }
  2196. }
  2197. }
  2198. }
  2199. }
  2200. //全部OK
  2201. if (resultFlog)
  2202. {
  2203. SendTaskMessage($"检测执行成功", MessageLevel.Debug);
  2204. await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)1);
  2205. }
  2206. //存在NG
  2207. else
  2208. {
  2209. SendTaskMessage($"检测执行失败", MessageLevel.Alarm);
  2210. await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)2);
  2211. }
  2212. }
  2213. }
  2214. else
  2215. {
  2216. SendTaskMessage($"触发固定相机检测拍照信号已关闭", MessageLevel.Alarm);
  2217. await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)0);
  2218. }
  2219. }
  2220. }
  2221. //切换成自动运行模式
  2222. else if (addressConfig.AutoRunning.Address.Contains(tuple.nodeId))
  2223. {
  2224. if (tuple.value is bool state)
  2225. {
  2226. if (_LastAutoRunning != state)
  2227. {
  2228. _LastAutoRunning = state;
  2229. }
  2230. else
  2231. {
  2232. return;
  2233. }
  2234. if (state)
  2235. {
  2236. CurrentRunStatus();
  2237. SendTaskMessage("收到切换成自动模式", MessageLevel.Info);
  2238. }
  2239. }
  2240. }
  2241. //切换成维修模式
  2242. else if (addressConfig.ManualMode.Address.Contains(tuple.nodeId))
  2243. {
  2244. if (tuple.value is bool state)
  2245. {
  2246. if (_LastManualMode != state)
  2247. {
  2248. _LastManualMode = state;
  2249. }
  2250. else
  2251. {
  2252. return;
  2253. }
  2254. if (state)
  2255. {
  2256. ClearModeBackground = System.Windows.Media.Brushes.White;
  2257. RunModelBackground = System.Windows.Media.Brushes.White;
  2258. ManualModeBackground = System.Windows.Media.Brushes.Orange;
  2259. SendTaskMessage("收到切换成维修模式", MessageLevel.Info);
  2260. }
  2261. }
  2262. }
  2263. //切换成流线模式
  2264. else if (addressConfig.ClearMode.Address.Contains(tuple.nodeId))
  2265. {
  2266. if (tuple.value is bool state)
  2267. {
  2268. if (_LastClearMode != state)
  2269. {
  2270. _LastClearMode = state;
  2271. }
  2272. else
  2273. {
  2274. return;
  2275. }
  2276. if (state)
  2277. {
  2278. ClearModeBackground = System.Windows.Media.Brushes.Yellow;
  2279. RunModelBackground = System.Windows.Media.Brushes.White;
  2280. ManualModeBackground = System.Windows.Media.Brushes.White;
  2281. SendTaskMessage("收到切换成流线模式", MessageLevel.Info);
  2282. }
  2283. }
  2284. }
  2285. // 过站检查
  2286. else
  2287. {
  2288. for (int i = 0; i < 10; i++)
  2289. {
  2290. if (string.Format(addressConfig.In_MesCheck.Address, i).Contains(tuple.nodeId))
  2291. {
  2292. if (tuple.value is Int16 state)
  2293. {
  2294. if (_LastMesCheck[i] != state)
  2295. {
  2296. _LastMesCheck[i] = state;
  2297. }
  2298. else
  2299. {
  2300. return;
  2301. }
  2302. var sysConfig = _configService.GetSystemConfiguration();
  2303. if (sysConfig.CodeUse == true && state == 1)
  2304. {
  2305. await plc.WriteNodeAsync(string.Format(addressConfig.Out_MesStatus.Address, i), (Int16)1);
  2306. return;
  2307. }
  2308. if (sysConfig.CodeUse2 == true && state == 1)
  2309. {
  2310. await plc.WriteNodeAsync(string.Format(addressConfig.Out_MesStatus.Address, i), (Int16)1);
  2311. return;
  2312. }
  2313. if (sysConfig.CodeUse == false && sysConfig.CodeUse2 == false)
  2314. {
  2315. code = plc.ReadNode<string>(string.Format(addressConfig.In_Code.Address, i));
  2316. }
  2317. var homeview = _container.Resolve<HomeViewModel>();
  2318. //过站检查
  2319. if (state == 1)
  2320. {
  2321. //这里缺少从MES获取产品配方的内容,需要补充
  2322. _LastMesCheckTime[i] = (await _mesService.GetServerTimeAsync(code, 2)).Now;
  2323. if (homeview.IsNoCode == false)
  2324. {
  2325. var device = _configService.GetDeviceInfo(0);
  2326. code = device.XnSN;
  2327. }
  2328. LogHelper.WriteLogMes($"【mes开始QUERY】");
  2329. SendTaskMessage($"mes开始QUERY", MessageLevel.Info);
  2330. ShowMes_Query = false;
  2331. (bool isSuccess, string response) = await _mesService.StationGetAsync(code, "", 2);//询问mes
  2332. if (i == 0)
  2333. {
  2334. SendTaskMessage($"收到当前过站检查请求(当站是否生产)...", MessageLevel.Debug);
  2335. }
  2336. else
  2337. {
  2338. SendTaskMessage($"收到{i}过站检查请求(当站是否生产)...", MessageLevel.Debug);
  2339. }
  2340. if (isSuccess)
  2341. {
  2342. string[] item = response.Split('\n');
  2343. //获取产品主sn和wo用于后续上传数据使用
  2344. string snItem = item.FirstOrDefault(f => f.Contains("sn="));
  2345. if (snItem != null)
  2346. {
  2347. ProductMainSN = snItem.Replace("sn=", "").Trim();
  2348. if (i == 0)
  2349. {
  2350. _productService.CurrentProductCode = ProductMainSN;
  2351. }
  2352. SendTaskMessage($"产品主sn:{ProductMainSN[i]}", MessageLevel.Info);
  2353. }
  2354. string woItem = item.FirstOrDefault(f => f.Contains("wo="));
  2355. if (woItem != null)
  2356. {
  2357. wo = woItem.Replace("wo=", "").Trim();
  2358. SendTaskMessage($"工单信息:{wo[i]}", MessageLevel.Info);
  2359. }
  2360. string modelItem = item.FirstOrDefault(f => f.Contains("model_num="));
  2361. if (modelItem != null)
  2362. {
  2363. model_num = modelItem.Replace("model_num=", "").Trim();
  2364. SendTaskMessage($"model_num:{model_num}", MessageLevel.Info);
  2365. }
  2366. string colorItem = item.FirstOrDefault(f => f.Contains("color="));
  2367. if (colorItem != null)
  2368. {
  2369. color = colorItem.Replace("color=", "").Trim();
  2370. SendTaskMessage($"color:{color}", MessageLevel.Info);
  2371. }
  2372. string ppidItem = item.FirstOrDefault(f => f.Contains("ppid="));
  2373. if (ppidItem != null)
  2374. {
  2375. ppid = ppidItem.Replace("ppid=", "").Trim();
  2376. SendTaskMessage($"ppid:{ppid}", MessageLevel.Info);
  2377. }
  2378. string stageItem = item.FirstOrDefault(f => f.Contains("stage="));
  2379. if (stageItem != null)
  2380. {
  2381. stage = stageItem.Replace("stage=", "").Trim();
  2382. SendTaskMessage($"stage:{revision}", MessageLevel.Info);
  2383. }
  2384. ShowMes_Query = true;
  2385. //产品发生改变并且供料器发生了变化时,需要通知PLC进行取料更改
  2386. //切换产品
  2387. if (i == 0)//i=0时才会切换产品
  2388. {
  2389. var q = await _systemDatabaseService.QueryProductFromMesAsync(model_num, color);
  2390. if (!string.IsNullOrEmpty(q))
  2391. {
  2392. ProductList = new ObservableCollection<ProductModel>(_productService.GetAllProducts());
  2393. Guid productId = Guid.Empty;
  2394. foreach (var itt in ProductList)
  2395. {
  2396. if (itt.Name == q)
  2397. {
  2398. productId = itt.ID;
  2399. break;
  2400. }
  2401. }
  2402. if (currentProduct.ID != productId)
  2403. {
  2404. //切换产品
  2405. _productService.LoadProduct(productId);
  2406. _productService.SetCurrentProduct(productId);
  2407. await WritePositionToPlcAsync();
  2408. SendTaskMessage($"切换产品成功", MessageLevel.Debug);
  2409. }
  2410. }
  2411. }
  2412. await plc.WriteNodeAsync(string.Format(addressConfig.Out_MesStatus.Address, i), (Int16)1);
  2413. LogHelper.WriteLogMes($"【mes结束QUERY】");
  2414. SendTaskMessage($"mes结束QUERY", MessageLevel.Info);
  2415. return;
  2416. }
  2417. else
  2418. {
  2419. //产品发生改变并且供料器发生了变化时,需要通知PLC进行取料更改
  2420. await plc.WriteNodeAsync(string.Format(addressConfig.Out_MesStatus.Address, i), (Int16)2);
  2421. LogHelper.WriteLogMes($"询问mes失败");
  2422. SendTaskMessage($"询问mes失败:{response}", MessageLevel.Error);
  2423. }
  2424. LogHelper.WriteLogMes($"【mes结束QUERY】");
  2425. SendTaskMessage($"mes结束QUERY", MessageLevel.Info);
  2426. }
  2427. // 上传本站数据
  2428. else if (state == 2)
  2429. {
  2430. //获取当前工位的配置
  2431. var stationConfig = _configService.GetDeviceInfo(0);
  2432. List<DataFormCtq> DFC = new List<DataFormCtq>();
  2433. SendTaskMessage($"收到{i}上传本站数据请求...", MessageLevel.Debug);
  2434. //这里缺少上传MES的本站数据结果及开始和结束时间,需要补充
  2435. //从服务器中获取当前时间
  2436. var serverTimeResult = await _mesService.GetServerTimeAsync(ProductMainSN, 2);
  2437. double ct = serverTimeResult.Now.Subtract(_LastMesCheckTime[i]).TotalSeconds;
  2438. if (i == 0)
  2439. {
  2440. CTtime = ct;
  2441. }
  2442. //读取产品结果
  2443. Int16 resultIndex = plc.ReadNode<Int16>(string.Format(addressConfig.In_Result.Address, i));
  2444. if (homeview.IsResultTrue == false)
  2445. {
  2446. resultIndex = 1;
  2447. }
  2448. //Int16 resultIndex = 1;
  2449. //目前只记录当前站
  2450. if (i == 0)
  2451. await _systemDatabaseService.RecordProductionAsync(new ProductionRecord()
  2452. {
  2453. ProductName = currentProduct.Name,
  2454. ProductCode = ProductMainSN,
  2455. DeviceId = i,
  2456. DeviceName = "",
  2457. Category = resultIndex == 1 ? "OK" : "NG",
  2458. Quantity = 1,
  2459. Remark = $"TotalSeconds:{DateTime.UtcNow.Subtract(_LastMesCheckTime[i]).TotalSeconds.ToString("F2")}",
  2460. });
  2461. LogHelper.WriteLogMes($"【mes开始ADD】");
  2462. SendTaskMessage($"mes开始ADD", MessageLevel.Info);
  2463. StringBuilder submitDataError = new StringBuilder();
  2464. foreach (var item in lockResultsAll)
  2465. {
  2466. if (item.PhotoPassed == "NG")
  2467. {
  2468. submitDataError.Append(item.PhotoName + "_Fail,");
  2469. }
  2470. }
  2471. StringBuilder submitData = new StringBuilder();
  2472. StringBuilder submitData2 = new StringBuilder();
  2473. StringBuilder submitData3 = new StringBuilder();
  2474. StringBuilder submitData4 = new StringBuilder();
  2475. foreach (var item in lockResultsAll)
  2476. {
  2477. //if (submitData.Length < 3500)
  2478. //{
  2479. // submitData.Append($"{item.PhotoName}={item.ResultData}");
  2480. //}
  2481. string data = $"{item.PhotoName}={item.ResultData}&";
  2482. // 按顺序填满,不超过 3500 就加进去
  2483. if (submitData.Length + data.Length <= 3500)
  2484. {
  2485. submitData.Append(data);
  2486. }
  2487. else if (submitData2.Length + data.Length <= 3500)
  2488. {
  2489. submitData2.Append(data);
  2490. }
  2491. else if (submitData3.Length + data.Length <= 3500)
  2492. {
  2493. submitData3.Append(data);
  2494. }
  2495. else if (submitData4.Length + data.Length <= 3500)
  2496. {
  2497. submitData4.Append(data);
  2498. }
  2499. else
  2500. {
  2501. SendTaskMessage($"上传数据数据超出4组最大限制", MessageLevel.Error);
  2502. }
  2503. }
  2504. bool allSuccess = true;
  2505. bool ok = CheckKeyBoardValue(keyData, out string msg);
  2506. if (ok && resultIndex == 1 ? true : false && isValueOk)
  2507. {
  2508. ShowMes_Result = true;
  2509. }
  2510. else
  2511. {
  2512. ShowMes_Result = false;
  2513. }
  2514. // ShowMes_Result = resultIndex == 1 ? true : false;
  2515. //(bool isSuccess, string response) = await _mesService.SubmitGetAsync(ProductMainSN, "", submitData.ToString(), resultIndex == 1 ? true : false, _LastMesCheckTime[i], serverTimeResult.Now);
  2516. if (submitData.Length > 0)
  2517. {
  2518. string data1 = submitData.ToString().TrimEnd('&');
  2519. (bool isSuccess, string response) = await _mesService.SubmitGetAsync(0,ProductMainSN, "", submitData.ToString(), ShowMes_Result, submitDataError.ToString(), _LastMesCheckTime[i], serverTimeResult.Now);
  2520. allSuccess &= isSuccess;
  2521. }
  2522. if (submitData2.Length > 0)
  2523. {
  2524. string data2 = submitData2.ToString().TrimEnd('&');
  2525. (bool isSuccess, string response) = await _mesService.SubmitGetAsync(1, ProductMainSN, "", submitData2.ToString(), ShowMes_Result, submitDataError.ToString(), _LastMesCheckTime[i], serverTimeResult.Now);
  2526. allSuccess &= isSuccess;
  2527. }
  2528. if (submitData3.Length > 0)
  2529. {
  2530. string data3 = submitData3.ToString().TrimEnd('&');
  2531. (bool isSuccess, string response) = await _mesService.SubmitGetAsync(2, ProductMainSN, "", submitData3.ToString(), ShowMes_Result , submitDataError.ToString(), _LastMesCheckTime[i], serverTimeResult.Now);
  2532. allSuccess &= isSuccess;
  2533. }
  2534. if (submitData4.Length > 0)
  2535. {
  2536. string data4 = submitData4.ToString().TrimEnd('&');
  2537. (bool isSuccess, string response) = await _mesService.SubmitGetAsync(3, ProductMainSN, "", submitData4.ToString(), ShowMes_Result, submitDataError.ToString(), _LastMesCheckTime[i], serverTimeResult.Now);
  2538. allSuccess &= isSuccess;
  2539. }
  2540. if (allSuccess)
  2541. {
  2542. LogHelper.WriteLogMes($"上传mes成功");
  2543. SendTaskMessage($"上传mes成功", MessageLevel.Debug);
  2544. }
  2545. else
  2546. {
  2547. LogHelper.WriteLogMes($"上传mes失败");
  2548. SendTaskMessage($"上传mes失败", MessageLevel.Error);
  2549. }
  2550. await plc.WriteNodeAsync(string.Format(addressConfig.Out_MesStatus.Address, i), (Int16)3);
  2551. //是否保存当前的产品记录至CSV?
  2552. if (stationConfig.SaveCsv)
  2553. {
  2554. string saveppid = "NA";
  2555. if (stationConfig.SaveCsvPPID) saveppid = ppid;
  2556. //判断锁付路径字符串是否为空,如果不为空则保存,否则不保存
  2557. if (!string.IsNullOrEmpty(stationConfig.SaveCsvPath))
  2558. {
  2559. foreach (var item in lockResultsAll)
  2560. {
  2561. for (int k = 1; k <= 8; k++)
  2562. {
  2563. if (item.PhotoName == "-" + "_" + k.ToString())
  2564. {
  2565. item.PhotoName = "'-" + "_" + k.ToString();
  2566. }
  2567. if (item.PhotoName == "=" + "_" + k.ToString())
  2568. {
  2569. item.PhotoName = "'=" + "_" + k.ToString();
  2570. }
  2571. }
  2572. DFC.Add(new DataFormCtq
  2573. {
  2574. PPID = saveppid,
  2575. PROCESS_NAME = stationConfig.DataInfo.PROCESS_NAME,
  2576. PROCESS_START_TIME = _LastMesCheckTime[i].ToString("o"),
  2577. CTQ_NAME = item.PhotoName,
  2578. CTQ_VALUE = item.ResultData.Replace(",", ";"),
  2579. CTQ_LSL = item.DownLimit,
  2580. CTQ_USL = item.UpLimit,
  2581. PROCESS_END_TIME = serverTimeResult.Now.ToString("o"),
  2582. SUPPLIER_NAME = stationConfig.DataInfo.SUPPLIER_NAME,
  2583. COMMODITY_TYPE = stationConfig.DataInfo.COMMODITY_TYPE,
  2584. REVISION = stage,//
  2585. WO = wo,//
  2586. MFG_LOT = stationConfig.DataInfo.MFG_LOT,//
  2587. MFG_ASSY_LINE = stationConfig.DataInfo.MFG_ASSY_LINE,
  2588. PROCESS_OUTCOME = item.PhotoPassed == "OK" ? "PASS" : "FAIL",
  2589. PROCESS_MACHINE_ID = stationConfig.DataInfo.PROCESS_MACHINE_ID,
  2590. CTQ_UNIT_OF_MEASURE = "mm",
  2591. ERROR_MESSAGE = item.PhotoPassed == "OK" ? "" : $"{item.PhotoName} OOS",
  2592. PD_ATTR_01 = ProductMainSN,//
  2593. PD_ATTR_02 = item.MidLimit,
  2594. PD_ATTR_03 = "",
  2595. PD_ATTR_04 = code,
  2596. PD_ATTR_05 = ""
  2597. });
  2598. }
  2599. bool recordResult = RecordStationResult(i, DFC, ProductMainSN, serverTimeResult.Now.Subtract(_LastMesCheckTime[i]).TotalSeconds, _LastMesCheckTime[i], stationConfig.SaveCsvPath);
  2600. if (recordResult)
  2601. {
  2602. SendTaskMessage($"{i}:{stationConfig.DeviceName}产品记录保存成功", MessageLevel.Debug);
  2603. //上传数据
  2604. try
  2605. {
  2606. if (stationConfig.EnableMES)
  2607. {
  2608. DateTime dt = DateTime.Now;
  2609. string filename = $"{ProductMainSN}_{dt.ToString("yyyyMMddHHmmss")}";
  2610. var device = _configService.GetDeviceInfo(i);
  2611. var config = _configService.GetSystemConfiguration();
  2612. string filePath = "";
  2613. (bool isSuc, string resp) = await _mesService.SendFtpFileAsync(ProductMainSN, filename);
  2614. if (isSuc)
  2615. {
  2616. LogHelper.WriteLogMes($"上传数据成功");
  2617. SendTaskMessage($"上传数据成功", MessageLevel.Debug);
  2618. //filePath = $"D:\\Image\\Recored\\{dt.ToString("yyyy-MM")}\\{dt.ToString("MM-dd")}\\{currentProduct.Name}\\{ProductMainSN}";
  2619. filePath = $"{PhotoPath}\\Recored\\{dt.ToString("yyyy-MM")}\\{dt.ToString("MM-dd")}\\{currentProduct.Name}\\{ProductMainSN}";
  2620. //string source_csv2 = $"{stationConfig.SaveCsvPath}\\{dt.ToString("yyyy-MM")}\\{i}_{stationConfig.DeviceName}_{dt.ToString("yyyy-MM-dd")}";
  2621. string csvfilename = $"{i}_{stationConfig.DeviceName}_{dt.ToString("yyyy-MM-dd")}";
  2622. //复制csv
  2623. string source_csv = $"{stationConfig.SaveCsvPath}\\{dt.ToString("yyyy-MM")}\\{i}_{stationConfig.DeviceName}_{dt.ToString("yyyy-MM-dd")}.csv";
  2624. //string source_csv1 = $"{stationConfig.SaveCsvPath}\\{dt.ToString("yyyy-MM")}";
  2625. string target_csv = Path.Combine(filePath, Path.GetFileName(source_csv));
  2626. File.Copy(source_csv, target_csv, true);
  2627. //复制log
  2628. string source_log = $"..\\Log\\LogInfo\\{dt.ToString("yyyy-MM")}\\{dt.ToString("yyyy-MM-dd")}.txt";
  2629. string target_log = Path.Combine(filePath, Path.GetFileName(source_log));
  2630. File.Copy(source_log, target_log, true);
  2631. CompressionImage(filePath, filename, device.Station, device.FixtureId);
  2632. //上传csv
  2633. bool isAfter20 = dt.Hour >= 20;
  2634. //判断是否是新的一天
  2635. bool isNewDay = dt.Date != _lastCompressDate.Date;
  2636. //当天还没执行过压缩
  2637. if (isAfter20 && isNewDay && !_hasCompressedToday)
  2638. {
  2639. // 执行压缩
  2640. CompressionSingleCsv(source_csv, csvfilename, device.Station, device.FixtureId);
  2641. _lastCompressDate = dt;
  2642. _hasCompressedToday = true;
  2643. LogHelper.WriteLogMes("csv上传数据成功");
  2644. SendTaskMessage($"csv上传数据成功", MessageLevel.Debug);
  2645. }
  2646. // 跨天后重置当天执行标记
  2647. if (!isNewDay && _hasCompressedToday)
  2648. {
  2649. _hasCompressedToday = false;
  2650. }
  2651. }
  2652. else
  2653. {
  2654. LogHelper.WriteLogMes($"上传数据失败");
  2655. SendTaskMessage($"上传数据失败", MessageLevel.Error);
  2656. }
  2657. }
  2658. else
  2659. {
  2660. LogHelper.WriteLogMes($"未启用mes");
  2661. SendTaskMessage($"未启用mes", MessageLevel.Error);
  2662. }
  2663. }
  2664. catch (Exception ex)
  2665. {
  2666. SendTaskMessage($"上传数据时出错:{ex.Message}", MessageLevel.Error);
  2667. LogHelper.WriteLogError($"上传数据时出错", ex);
  2668. }
  2669. }
  2670. else
  2671. {
  2672. SendTaskMessage($"{i}:{stationConfig.DeviceName}产品记录保存失败", MessageLevel.Error);
  2673. }
  2674. }
  2675. else
  2676. {
  2677. SendTaskMessage($"{i}:{stationConfig.DeviceName}工位未配置保存路径,无法保存产品记录", MessageLevel.Error);
  2678. }
  2679. }
  2680. else
  2681. {
  2682. SendTaskMessage($"{i}:{stationConfig.DeviceName}工位未配置保存产品记录", MessageLevel.Debug);
  2683. }
  2684. //WriteProductLog(lockResultsAll, code, CTtime);
  2685. lock (_stateLock)
  2686. {
  2687. lockResultsAll.Clear();
  2688. }
  2689. ProductMainSN = "";
  2690. LogHelper.WriteLogMes($"【mes结束ADD】");
  2691. SendTaskMessage($"mes结束ADD", MessageLevel.Info);
  2692. }
  2693. else
  2694. {
  2695. SendTaskMessage($"{i}过站检查信号:state={state},处理为默认状态", MessageLevel.Alarm);
  2696. await plc.WriteNodeAsync(string.Format(addressConfig.Out_MesStatus.Address, i), (Int16)0);
  2697. }
  2698. }
  2699. }
  2700. }
  2701. }
  2702. }
  2703. catch (Exception ex)
  2704. {
  2705. SendTaskMessage(ex.Message, MessageLevel.Error);
  2706. }
  2707. }
  2708. /// <summary>
  2709. /// 异步执行流程拍照
  2710. /// </summary>
  2711. /// <param name="pointIndex"></param>
  2712. /// <param name="procedureId"></param>
  2713. /// <returns></returns>
  2714. private Task<(bool IsSucceed, bool[] Result, string Message)> ExecuteProcedureAsync(int pointIndex, Guid procedureId)
  2715. {
  2716. return Task.Run(async () =>
  2717. {
  2718. List<bool> results = new List<bool>();
  2719. // 获取当前产品
  2720. var currentProduct = _productService.GetCurrentProduct();
  2721. if (currentProduct == null)
  2722. {
  2723. return (false, null, "当前产品为空,未加载产品!");
  2724. }
  2725. var cameraProcedures = currentProduct.CameraProcedures;
  2726. if (cameraProcedures == null || cameraProcedures.Count == 0)
  2727. {
  2728. SendTaskMessage($"当前产品未配置 CameraProcedures,无法执行视觉流程", MessageLevel.Alarm);
  2729. return (false, null, $"当前产品未配置 CameraProcedures,无法执行视觉流程");
  2730. }
  2731. var ctsAll = new CancellationTokenSource();
  2732. try
  2733. {
  2734. ProcedureModel selectedProcedure = null;
  2735. try
  2736. {
  2737. foreach (var cp in cameraProcedures)
  2738. {
  2739. if (cp?.ProcedureModels == null) continue;
  2740. selectedProcedure = cp.ProcedureModels.FirstOrDefault(pm => pm.Id == procedureId);
  2741. if (selectedProcedure != null) break;
  2742. }
  2743. }
  2744. catch (Exception ex)
  2745. {
  2746. LogHelper.WriteLogError("查找 AOI 点位对应视觉流程时出错", ex);
  2747. }
  2748. if (selectedProcedure == null)
  2749. {
  2750. SendTaskMessage($"未找到 AOI 点位对应的视觉流程,Point#{pointIndex} ProcedureId={pointIndex}", MessageLevel.Alarm);
  2751. return (false, null, $"未找到 AOI 点位对应的视觉流程,Point#{pointIndex} ProcedureId={procedureId}");
  2752. }
  2753. SendTaskMessage($"开始执行 AOI 流程 (Point#{pointIndex}) 流程Id={pointIndex}", MessageLevel.Debug);
  2754. try
  2755. {
  2756. //1. 执行拍照,图像处理
  2757. var visionResult = await _remoteCommandService.ExecutePhotoGetSinglePoint1(selectedProcedure, null, null, ctsAll.Token);
  2758. if (visionResult.Count == 0)
  2759. {
  2760. SendTaskMessage("Count值为0", MessageLevel.Alarm);
  2761. return (false, null, $"未找到 AOI 点位对应的视觉流程,Point#{pointIndex} ProcedureId={procedureId}");
  2762. }
  2763. //2. 结果分析
  2764. for (int i = 1; i <= visionResult.Count; i++)
  2765. {
  2766. LockResult lockResult1 = new LockResult();
  2767. //if (pointIndex == currentProduct.PhotoCount && selectedProcedure.Id == currentProduct.FixedUpCamera1ProcedureId && i == 1)
  2768. //{
  2769. // lockResult1.Number = 1;
  2770. //}
  2771. string[] strpoints1 = visionResult.Items[i].Split(',');
  2772. lockResult1.PhotoName = strpoints1[0];
  2773. string[] body1 = strpoints1[1].Split(";");
  2774. string body2 = null;
  2775. if (body1.Length == 8)
  2776. {
  2777. body2 = $"{body1[0]},{body1[2]},{body1[4]},{body1[6]}";
  2778. }
  2779. else
  2780. {
  2781. body2 = strpoints1[1];
  2782. }
  2783. lockResult1.ResultData = body2;
  2784. lockResult1.PhotoCode = ProductMainSN;
  2785. var globalParam = currentProduct.GlobalParamListCollection.FirstOrDefault(p => p.Name == strpoints1[0]);
  2786. if (globalParam != null)
  2787. {
  2788. lockResult1.UpLimit = globalParam.Param1;
  2789. lockResult1.DownLimit = globalParam.Param2;
  2790. lockResult1.MidLimit = globalParam.Param5;
  2791. string ResData = strpoints1[1];
  2792. if (ResData.Contains("NA"))
  2793. {
  2794. ResData = "-1000";
  2795. }
  2796. string[] body = ResData.Split(";");
  2797. bool resultflog = true;
  2798. foreach (var item in body)
  2799. {
  2800. if (Convert.ToDouble(item) >= Convert.ToDouble(globalParam.Param2) && Convert.ToDouble(item) <= Convert.ToDouble(globalParam.Param1))
  2801. {
  2802. }
  2803. else
  2804. {
  2805. resultflog = false;
  2806. }
  2807. }
  2808. if (resultflog)
  2809. {
  2810. lockResult1.PhotoPassed = "OK";
  2811. results.Add(true);
  2812. }
  2813. else
  2814. {
  2815. lockResult1.PhotoPassed = "NG";
  2816. results.Add(false);
  2817. }
  2818. }
  2819. lock (_stateLock)
  2820. {
  2821. lockResultsAll.Add(lockResult1);
  2822. }
  2823. App.Current.Dispatcher.Invoke(() =>
  2824. {
  2825. _eventAggregator.GetEvent<LockFinishNotification>().Publish(lockResult1);
  2826. });
  2827. }
  2828. //排序
  2829. //lock (_stateLock)
  2830. //{
  2831. // var bf1 = lockResultsAll.OrderBy(p => p.Number);
  2832. // lockResultsAll = new List<LockResult>(bf1);
  2833. //}
  2834. }
  2835. catch (Exception ex)
  2836. {
  2837. LogHelper.WriteLogError("执行 AOI 视觉流程时出错", ex);
  2838. SendTaskMessage($"执行 AOI 视觉流程异常: {ex.Message}", MessageLevel.Alarm);
  2839. }
  2840. return (true, results.ToArray(), $"成功");
  2841. }
  2842. catch (Exception ex)
  2843. {
  2844. LogHelper.WriteLogError("处理固定相机检测拍照时出错", ex);
  2845. return (false, null, $"处理固定相机检测拍照时出错");
  2846. }
  2847. });
  2848. }
  2849. /// <summary>
  2850. /// 异步执行流程拍照
  2851. /// </summary>
  2852. /// <param name="pointIndex"></param>
  2853. /// <param name="procedureId"></param>
  2854. /// <returns></returns>
  2855. private Task<(bool IsSucceed, bool[] Result, string Message)> ExecuteProcedureAsync(int pointIndex, Guid procedureId, ICogImage[] images, bool is3dmodel)
  2856. {
  2857. return Task.Run(async () =>
  2858. {
  2859. List<bool> results = new List<bool>();
  2860. // 获取当前产品
  2861. var currentProduct = _productService.GetCurrentProduct();
  2862. if (currentProduct == null)
  2863. {
  2864. return (false, null, "当前产品为空,未加载产品!");
  2865. }
  2866. var cameraProcedures = currentProduct.CameraProcedures;
  2867. if (cameraProcedures == null || cameraProcedures.Count == 0)
  2868. {
  2869. SendTaskMessage($"当前产品未配置 CameraProcedures,无法执行视觉流程", MessageLevel.Alarm);
  2870. return (false, null, $"当前产品未配置 CameraProcedures,无法执行视觉流程");
  2871. }
  2872. var ctsAll = new CancellationTokenSource();
  2873. try
  2874. {
  2875. ProcedureModel selectedProcedure = null;
  2876. try
  2877. {
  2878. foreach (var cp in cameraProcedures)
  2879. {
  2880. if (cp?.ProcedureModels == null) continue;
  2881. selectedProcedure = cp.ProcedureModels.FirstOrDefault(pm => pm.Id == procedureId);
  2882. if (selectedProcedure != null) break;
  2883. }
  2884. }
  2885. catch (Exception ex)
  2886. {
  2887. LogHelper.WriteLogError("查找 AOI 点位对应视觉流程时出错", ex);
  2888. }
  2889. if (selectedProcedure == null)
  2890. {
  2891. SendTaskMessage($"未找到 AOI 点位对应的视觉流程,Point#{pointIndex} ProcedureId={pointIndex}", MessageLevel.Alarm);
  2892. return (false, null, $"未找到 AOI 点位对应的视觉流程,Point#{pointIndex} ProcedureId={procedureId}");
  2893. }
  2894. SendTaskMessage($"开始执行 AOI 流程 (Point#{pointIndex}) 流程Id={pointIndex}", MessageLevel.Debug);
  2895. try
  2896. {
  2897. var sysConfig = _configService.GetSystemConfiguration();
  2898. if (selectedProcedure.Id == currentProduct.MoveDownCameraLockPhotoProcedureId && sysConfig.TurnOffAllLightUse == true)
  2899. {
  2900. await _remoteCommandService.TurnOffLightAfterPhoto(selectedProcedure);
  2901. }
  2902. PhotoPath = selectedProcedure.SavePath;
  2903. //1. 执行拍照,图像处理
  2904. var visionResult = await _remoteCommandService.ExecutePhotoGetSinglePoint1(selectedProcedure, images, null, null, ctsAll.Token, is3dmodel);
  2905. if (visionResult.Count == 0)
  2906. {
  2907. SendTaskMessage("Count值为0", MessageLevel.Alarm);
  2908. return (false, null, $"未找到 AOI 点位对应的视觉流程,Point#{pointIndex} ProcedureId={procedureId}");
  2909. }
  2910. //2. 结果分析
  2911. lock (_stateLock)
  2912. {
  2913. for (int i = 1; i <= visionResult.Count; i++)
  2914. {
  2915. LockResult lockResult1 = new LockResult();
  2916. //if (pointIndex == currentProduct.PhotoCount && selectedProcedure.Id == currentProduct.FixedUpCamera1ProcedureId && i == 1)
  2917. //{
  2918. // lockResult1.Number = 1;
  2919. // lock (_stateLock)
  2920. // {
  2921. // lockResultsAll.Clear();
  2922. // }
  2923. //}
  2924. try
  2925. {
  2926. string[] strpoints1 = visionResult.Items[i].Split(',');
  2927. string[] body1 = strpoints1[1].Split(";");
  2928. string keyName = strpoints1[0].Split('-').Last().Trim();
  2929. List<double> list = new List<double>();
  2930. foreach (string v in body1)
  2931. {
  2932. if (double.TryParse(v.Trim(), out double num))
  2933. {
  2934. if (num == 999)
  2935. {
  2936. continue;
  2937. }
  2938. list.Add(num);
  2939. }
  2940. }
  2941. if (list.Count == 0)
  2942. {
  2943. continue;
  2944. }
  2945. double max = list.Max();
  2946. double min = list.Min();
  2947. if (max - min <= 0.3)
  2948. {
  2949. isValueOk = true;
  2950. }
  2951. else
  2952. {
  2953. SendTaskMessage($"键盘格{keyName}最大值{max}与最小值{min}相差大于0.3!",MessageLevel.Error);
  2954. }
  2955. double average = list.Average();
  2956. if (!keyData.ContainsKey(keyName))
  2957. keyData.Add(keyName, average);
  2958. if (body1.Length > 1)
  2959. {
  2960. for (int j = 1; j <= body1.Length; j++)
  2961. {
  2962. lockResult1.PhotoName = strpoints1[0] + "_" + j.ToString();
  2963. lockResult1.ResultData = body1[j - 1];
  2964. lockResult1.PhotoCode = ProductMainSN;
  2965. var globalParam = currentProduct.GlobalParamListCollection.FirstOrDefault(p => p.Name == strpoints1[0]);
  2966. if (globalParam != null)
  2967. {
  2968. lockResult1.UpLimit = globalParam.Param1;
  2969. lockResult1.DownLimit = globalParam.Param2;
  2970. lockResult1.MidLimit = globalParam.Param5;
  2971. string ResData = body1[j - 1];
  2972. if (ResData.Contains("NA"))
  2973. {
  2974. ResData = "-1000";
  2975. }
  2976. bool resultflog = true;
  2977. if (Convert.ToDouble(ResData) >= Convert.ToDouble(globalParam.Param2) && Convert.ToDouble(ResData) <= Convert.ToDouble(globalParam.Param1))
  2978. {
  2979. }
  2980. else
  2981. {
  2982. resultflog = false;
  2983. }
  2984. if (resultflog)
  2985. {
  2986. lockResult1.PhotoPassed = "OK";
  2987. results.Add(true);
  2988. }
  2989. else
  2990. {
  2991. lockResult1.PhotoPassed = "NG";
  2992. results.Add(false);
  2993. }
  2994. }
  2995. lockResultsAll.Add(lockResult1.Copy());
  2996. }
  2997. }
  2998. else
  2999. {
  3000. lockResult1.PhotoName = strpoints1[0];
  3001. lockResult1.ResultData = strpoints1[1];
  3002. lockResult1.PhotoCode = ProductMainSN;
  3003. var globalParam = currentProduct.GlobalParamListCollection.FirstOrDefault(p => p.Name == strpoints1[0]);
  3004. if (globalParam != null)
  3005. {
  3006. lockResult1.UpLimit = globalParam.Param1;
  3007. lockResult1.DownLimit = globalParam.Param2;
  3008. lockResult1.MidLimit = globalParam.Param5;
  3009. string ResData = strpoints1[1];
  3010. if (ResData.Contains("NA"))
  3011. {
  3012. ResData = "-1000";
  3013. }
  3014. bool resultflog = true;
  3015. if (Convert.ToDouble(ResData) >= Convert.ToDouble(globalParam.Param2) && Convert.ToDouble(ResData) <= Convert.ToDouble(globalParam.Param1))
  3016. {
  3017. }
  3018. else
  3019. {
  3020. resultflog = false;
  3021. }
  3022. if (resultflog)
  3023. {
  3024. lockResult1.PhotoPassed = "OK";
  3025. results.Add(true);
  3026. }
  3027. else
  3028. {
  3029. lockResult1.PhotoPassed = "NG";
  3030. results.Add(false);
  3031. }
  3032. }
  3033. lockResultsAll.Add(lockResult1);
  3034. }
  3035. }
  3036. catch (Exception ex)
  3037. {
  3038. SendTaskMessage($"拆分视觉结果出错:{ex}",MessageLevel.Error);
  3039. }
  3040. App.Current.Dispatcher.Invoke(() =>
  3041. {
  3042. _eventAggregator.GetEvent<LockFinishNotification>().Publish(lockResult1);
  3043. });
  3044. }
  3045. }
  3046. ////排序
  3047. //lock (_stateLock)
  3048. //{
  3049. // var bf1 = lockResultsAll.OrderBy(p => int.Parse(p.PhotoName));
  3050. // lockResultsAll = new List<LockResult>(bf1);
  3051. //}
  3052. }
  3053. catch (Exception ex)
  3054. {
  3055. LogHelper.WriteLogError("执行 AOI 视觉流程时出错", ex);
  3056. SendTaskMessage($"执行 AOI 视觉流程异常: {ex.Message}", MessageLevel.Alarm);
  3057. }
  3058. return (true, results.ToArray(), $"成功");
  3059. }
  3060. catch (Exception ex)
  3061. {
  3062. LogHelper.WriteLogError("处理固定相机检测拍照时出错", ex);
  3063. return (false, null, $"处理固定相机检测拍照时出错");
  3064. }
  3065. });
  3066. }
  3067. /// <summary>
  3068. /// 是否是3D相机
  3069. /// </summary>
  3070. /// <param name="procedureId"></param>
  3071. /// <returns></returns>
  3072. private bool Is3D(Guid procedureId)
  3073. {
  3074. // 获取当前产品
  3075. var currentProduct = _productService.GetCurrentProduct();
  3076. if (currentProduct == null)
  3077. {
  3078. return false;
  3079. }
  3080. var cameraProcedures = currentProduct.CameraProcedures;
  3081. if (cameraProcedures == null || cameraProcedures.Count == 0)
  3082. {
  3083. return false;
  3084. }
  3085. ProcedureModel selectedProcedure = null;
  3086. try
  3087. {
  3088. foreach (var cp in cameraProcedures)
  3089. {
  3090. if (cp?.ProcedureModels == null) continue;
  3091. selectedProcedure = cp.ProcedureModels.FirstOrDefault(pm => pm.Id == procedureId);
  3092. if (selectedProcedure != null) break;
  3093. }
  3094. }
  3095. catch (Exception ex)
  3096. {
  3097. LogHelper.WriteLogError("查找 AOI 点位对应视觉流程时出错", ex);
  3098. }
  3099. if (selectedProcedure == null)
  3100. {
  3101. return false;
  3102. }
  3103. var camera = _cameraService.GetCamera(selectedProcedure.CameraId);
  3104. if (camera == null)
  3105. {
  3106. return false;
  3107. }
  3108. return camera.Is3D;
  3109. }
  3110. /// <summary>
  3111. /// 2D相机先采集图像
  3112. /// </summary>
  3113. /// <param name="procedureId"></param>
  3114. /// <returns></returns>
  3115. private async Task<(bool IsSucceed, ICogImage[] imges, string Message)> GrabImage(int pointIndex, Guid procedureId)
  3116. {
  3117. // 获取当前产品
  3118. var currentProduct = _productService.GetCurrentProduct();
  3119. if (currentProduct == null)
  3120. {
  3121. return (false, null, "当前产品为空,未加载产品!");
  3122. }
  3123. var cameraProcedures = currentProduct.CameraProcedures;
  3124. if (cameraProcedures == null || cameraProcedures.Count == 0)
  3125. {
  3126. SendTaskMessage($"当前产品未配置 CameraProcedures,无法执行视觉流程", MessageLevel.Alarm);
  3127. return (false, null, $"当前产品未配置 CameraProcedures,无法执行视觉流程");
  3128. }
  3129. try
  3130. {
  3131. ProcedureModel selectedProcedure = null;
  3132. try
  3133. {
  3134. foreach (var cp in cameraProcedures)
  3135. {
  3136. if (cp?.ProcedureModels == null) continue;
  3137. selectedProcedure = cp.ProcedureModels.FirstOrDefault(pm => pm.Id == procedureId);
  3138. if (selectedProcedure != null) break;
  3139. }
  3140. }
  3141. catch (Exception ex)
  3142. {
  3143. LogHelper.WriteLogError("查找 AOI 点位对应视觉流程时出错", ex);
  3144. }
  3145. if (selectedProcedure == null)
  3146. {
  3147. SendTaskMessage($"未找到 AOI 点位对应的视觉流程,Point#{pointIndex} ProcedureId={pointIndex}", MessageLevel.Alarm);
  3148. return (false, null, $"未找到 AOI 点位对应的视觉流程,Point#{pointIndex} ProcedureId={procedureId}");
  3149. }
  3150. SendTaskMessage($"开始执行 AOI 流程 (Point#{pointIndex}) 流程Id={pointIndex}", MessageLevel.Debug);
  3151. try
  3152. {
  3153. var sysConfig = _configService.GetSystemConfiguration();
  3154. if (selectedProcedure.Id == currentProduct.FixedDownCameraProcedureId && sysConfig.TurnOnAllLightUse == true)
  3155. {
  3156. await _remoteCommandService.SetLightBeforePhoto(selectedProcedure);
  3157. }
  3158. //1. 执行拍照
  3159. //return await _remoteCommandService.ExecuteGrabImageAsync(selectedProcedure);
  3160. }
  3161. catch (Exception ex)
  3162. {
  3163. LogHelper.WriteLogError("执行 AOI 视觉图像采集时出错", ex);
  3164. SendTaskMessage($"执行 AOI 视觉图像采集时出错: {ex.Message}", MessageLevel.Alarm);
  3165. }
  3166. return (false, null, $"图像采集失败");
  3167. }
  3168. catch (Exception ex)
  3169. {
  3170. LogHelper.WriteLogError("处理固定相机检测拍照时出错", ex);
  3171. return (false, null, $"处理固定相机检测拍照时出错");
  3172. }
  3173. }
  3174. /// <summary>
  3175. /// 为所有相机设置批处理点数(会调用具体相机实现的 SetBatchPoints)
  3176. /// </summary>
  3177. /// <param name="points"></param>
  3178. public void SetBatchPoints(int CameraNum, int points)
  3179. {
  3180. try
  3181. {
  3182. if (points == 0 || points < 0)
  3183. {
  3184. return;
  3185. }
  3186. var cameras = _cameraService.GetCameraByNumber(CameraNum);
  3187. if (cameras == null) return;
  3188. try
  3189. {
  3190. // 优先针对已知的 SSZNCamera 类型直接调用
  3191. if (cameras is TeamAAS_VP.Core.Cameras.SSZNCamera sszn)
  3192. {
  3193. sszn.CameraRevFinish = false;
  3194. sszn.SetBatchPoints(points);
  3195. }
  3196. }
  3197. catch (Exception ex)
  3198. {
  3199. LogHelper.WriteLogError($"SetBatchPoints to camera {cameras?.Name} failed", ex);
  3200. }
  3201. }
  3202. catch (Exception ex)
  3203. {
  3204. LogHelper.WriteLogError("SetBatchPoints failed", ex);
  3205. }
  3206. }
  3207. /// <summary>
  3208. /// 为所有相机设置产品配方(会调用具体相机实现的 SetBatchPoints)
  3209. /// </summary>
  3210. /// <param name="points"></param>
  3211. public void SetProducts(int CameraNum, int points)
  3212. {
  3213. try
  3214. {
  3215. if (points < 0)
  3216. {
  3217. return;
  3218. }
  3219. var cameras = _cameraService.GetCameraByNumber(CameraNum);
  3220. if (cameras == null) return;
  3221. try
  3222. {
  3223. // 优先针对已知的 SSZNCamera 类型直接调用
  3224. if (cameras is TeamAAS_VP.Core.Cameras.SSZNCamera sszn)
  3225. {
  3226. sszn.CameraRevFinish = false;
  3227. sszn.SetProducts(CameraNum,points);
  3228. }
  3229. }
  3230. catch (Exception ex)
  3231. {
  3232. LogHelper.WriteLogError($"SetBatchPoints to camera {cameras?.Name} failed", ex);
  3233. }
  3234. }
  3235. catch (Exception ex)
  3236. {
  3237. LogHelper.WriteLogError("SetBatchPoints failed", ex);
  3238. }
  3239. }
  3240. public void SetBatchPoints(int[] CameraSpoints)
  3241. {
  3242. try
  3243. {
  3244. for (int i = 0; i < CameraSpoints.Length; i++)
  3245. {
  3246. SetBatchPoints(i + 1, CameraSpoints[i]);
  3247. }
  3248. }
  3249. catch (Exception ex)
  3250. {
  3251. LogHelper.WriteLogError("SetBatchPoints failed", ex);
  3252. }
  3253. }
  3254. public void SetProducts(int[] CameraSpoints)
  3255. {
  3256. try
  3257. {
  3258. for (int i = 0; i < CameraSpoints.Length; i++)
  3259. {
  3260. SetProducts(i + 1, CameraSpoints[i]);
  3261. }
  3262. }
  3263. catch (Exception ex)
  3264. {
  3265. LogHelper.WriteLogError("SetProducts failed", ex);
  3266. }
  3267. }
  3268. #endregion
  3269. #region 方法
  3270. private void SendTaskMessage(string msg, MessageLevel level)
  3271. {
  3272. App.Current.Dispatcher.Invoke(() =>
  3273. {
  3274. _eventAggregator.GetEvent<TaskMessageNotification>().Publish(new Models.MessageStruct() { Message = msg, level = level });
  3275. });
  3276. }
  3277. public bool concurrenty = true;
  3278. public void CurrentRunStatus()
  3279. {
  3280. if (!concurrenty)
  3281. {
  3282. return;
  3283. }
  3284. concurrenty = true;
  3285. bool connectStaus = true;
  3286. bool mesStatus = true;
  3287. bool paraStatus = true;
  3288. try
  3289. {
  3290. var stationConfig = _configService.GetDeviceInfo(0);
  3291. if (!stationConfig.EnableMES || !stationConfig.EnableDoubleMes || !stationConfig.SaveCsv)
  3292. {
  3293. mesStatus = false;
  3294. }
  3295. foreach (var item in Status)
  3296. {
  3297. if (item.Background == System.Windows.Media.Brushes.Red)
  3298. {
  3299. connectStaus = false;
  3300. break;
  3301. }
  3302. }
  3303. }
  3304. catch (Exception)
  3305. {
  3306. connectStaus = false;
  3307. }
  3308. if (connectStaus && mesStatus && _LastAutoRunning)
  3309. {
  3310. RunModelBackground = System.Windows.Media.Brushes.Green;
  3311. ClearModeBackground = System.Windows.Media.Brushes.White;
  3312. ManualModeBackground = System.Windows.Media.Brushes.White;
  3313. SendTaskMessage("当前为运行模式", MessageLevel.Info);
  3314. }
  3315. else
  3316. {
  3317. RunModelBackground = System.Windows.Media.Brushes.White;
  3318. ClearModeBackground = System.Windows.Media.Brushes.White;
  3319. ManualModeBackground = System.Windows.Media.Brushes.Orange;
  3320. SendTaskMessage("当前为调机模式", MessageLevel.Info);
  3321. }
  3322. concurrenty = true;
  3323. }
  3324. /// <summary>
  3325. /// 校验键盘所有按键值,相邻差值不能大于 0.3
  3326. /// </summary>
  3327. public bool CheckKeyBoardValue(Dictionary<string, double> keyDic, out string errorMsg)
  3328. {
  3329. errorMsg = "";
  3330. try
  3331. {
  3332. // 2. 获取每个按键的【真实相邻按键】
  3333. Dictionary<string, List<string>> neighborMap = GetKeyboardNeighborMap();
  3334. // 3. 开始校验:每个按键 和 相邻按键 差值 ≤0.3
  3335. foreach (var item in keyDic)
  3336. {
  3337. string key = item.Key.ToUpper();
  3338. double val = item.Value;
  3339. // 没有相邻关系就跳过
  3340. if (!neighborMap.ContainsKey(key))
  3341. continue;
  3342. // 遍历所有相邻按键
  3343. foreach (string neighbor in neighborMap[key])
  3344. {
  3345. string n = neighbor.ToUpper();
  3346. if (!keyDic.ContainsKey(n))
  3347. continue;
  3348. double nVal = keyDic[n];
  3349. double diff = Math.Abs(val - nVal);
  3350. // 超过 0.3 直接报错
  3351. if (diff > 0.3)
  3352. {
  3353. SendTaskMessage($"按键 {key}({val}) 与相邻按键 {n}({nVal}) 差值 {diff:F3} > 0.3,校验不通过", MessageLevel.Error);
  3354. return false;
  3355. }
  3356. }
  3357. }
  3358. SendTaskMessage("所有键盘按键相邻差值校验通过", MessageLevel.Debug);
  3359. return true;
  3360. }
  3361. catch (Exception ex)
  3362. {
  3363. errorMsg = "校验异常:" + ex.Message;
  3364. return false;
  3365. }
  3366. }
  3367. /// <summary>
  3368. /// 键盘相邻关系
  3369. /// </summary>
  3370. private Dictionary<string, List<string>> GetKeyboardNeighborMap()
  3371. {
  3372. return new Dictionary<string, List<string>>
  3373. {
  3374. // ==============================================
  3375. // 第一行:ESC + F1~F12
  3376. // ==============================================
  3377. ["ESC"] = new List<string> { "F1", "`", "1" },
  3378. ["F1"] = new List<string> { "ESC", "F2", "`", "1", "2" },
  3379. ["F2"] = new List<string> { "F1", "F3", "1", "2", "3" },
  3380. ["F3"] = new List<string> { "F2", "F4", "2", "3", "4" },
  3381. ["F4"] = new List<string> { "F3", "F5", "3", "4", "5" },
  3382. ["F5"] = new List<string> { "F4", "F6", "4", "5", "6" },
  3383. ["F6"] = new List<string> { "F5", "F7", "5", "6", "7" },
  3384. ["F7"] = new List<string> { "F6", "F8", "6", "7", "8" },
  3385. ["F8"] = new List<string> { "F7", "F9", "7", "8", "9" },
  3386. ["F9"] = new List<string> { "F8", "F10", "8", "9", "0" },
  3387. ["F10"] = new List<string> { "F9", "F11", "9", "0", "-" },
  3388. ["F11"] = new List<string> { "F10", "F12", "0", "-", "=" },
  3389. ["F12"] = new List<string> { "F11", "-", "=", "Backspace" },
  3390. // ==============================================
  3391. // 第二行:` 1 2 3 4 5 6 7 8 9 0 - = Backspace
  3392. // ==============================================
  3393. ["`"] = new List<string> { "ESC", "F1", "1", "TAB", "Q" },
  3394. ["1"] = new List<string> { "ESC", "F1", "F2", "`", "2", "TAB", "Q" },
  3395. ["2"] = new List<string> { "F1", "F2", "F3", "1", "3", "Q", "W" },
  3396. ["3"] = new List<string> { "F2", "F3", "F4", "2", "4", "W", "E" },
  3397. ["4"] = new List<string> { "F3", "F4", "F5", "3", "5", "E", "R" },
  3398. ["5"] = new List<string> { "F4", "F5", "F6", "4", "6", "R", "T" },
  3399. ["6"] = new List<string> { "F5", "F6", "F7", "5", "7", "T", "Y" },
  3400. ["7"] = new List<string> { "F6", "F7", "F8", "6", "8", "Y", "U" },
  3401. ["8"] = new List<string> { "F7", "F8", "F9", "7", "9", "U", "I" },
  3402. ["9"] = new List<string> { "F8", "F9", "F10", "8", "0", "I", "O" },
  3403. ["0"] = new List<string> { "F9", "F10", "F11", "9", "-", "O", "P" },
  3404. ["-"] = new List<string> { "F10", "F11", "F12", "0", "=", "P", "[" },
  3405. ["="] = new List<string> { "F11", "F12", "-", "Backspace", "[", "]" },
  3406. ["Backspace"] = new List<string> { "F12", "=", "]", "\\" },
  3407. // ==============================================
  3408. // 第三行:TAB Q W E R T Y U I O P [ ] \
  3409. // ==============================================
  3410. ["TAB"] = new List<string> { "`", "1", "Q", "CapsLock" },
  3411. ["Q"] = new List<string> { "TAB", "`", "1", "2", "W", "A", "CapsLock" },
  3412. ["W"] = new List<string> { "Q", "1", "2", "3", "E", "A", "S" },
  3413. ["E"] = new List<string> { "W", "2", "3", "4", "R", "S", "D" },
  3414. ["R"] = new List<string> { "E", "3", "4", "5", "T", "D", "F" },
  3415. ["T"] = new List<string> { "R", "4", "5", "6", "Y", "F", "G" },
  3416. ["Y"] = new List<string> { "T", "5", "6", "7", "U", "G", "H" },
  3417. ["U"] = new List<string> { "Y", "6", "7", "8", "I", "H", "J" },
  3418. ["I"] = new List<string> { "U", "7", "8", "9", "O", "J", "K" },
  3419. ["O"] = new List<string> { "I", "8", "9", "0", "P", "K", "L" },
  3420. ["P"] = new List<string> { "O", "9", "0", "-", "[", "L", ";" },
  3421. ["["] = new List<string> { "P", "0", "-", "=", "]", ";", "'" },
  3422. ["]"] = new List<string> { "[", "-", "=", "Backspace", "\\", "'", "Enter" },
  3423. ["\\"] = new List<string> { "]", "=", "Backspace", "Enter" },
  3424. // ==============================================
  3425. // 第四行:CapsLock A S D F G H J K L ; ' Enter
  3426. // ==============================================
  3427. ["CapsLock"] = new List<string> { "TAB", "Q", "A", "LeftShift" },
  3428. ["A"] = new List<string> { "CapsLock", "Q", "W", "S", "LeftShift", "Z" },
  3429. ["S"] = new List<string> { "A", "W", "E", "D", "Z", "X", "LeftShift" },
  3430. ["D"] = new List<string> { "S", "E", "R", "F", "X", "C", "LeftShift" },
  3431. ["F"] = new List<string> { "D", "R", "T", "G", "C", "V" },
  3432. ["G"] = new List<string> { "F", "T", "Y", "H", "V", "B" },
  3433. ["H"] = new List<string> { "G", "Y", "U", "J", "B", "N" },
  3434. ["J"] = new List<string> { "H", "U", "I", "K", "N", "M" },
  3435. ["K"] = new List<string> { "J", "I", "O", "L", "M", "," },
  3436. ["L"] = new List<string> { "K", "O", "P", ";", ",", ".", "/" },
  3437. [";"] = new List<string> { "L", "P", "[", "'", ".", "/" },
  3438. ["'"] = new List<string> { ";", "[", "]", "Enter", "/" },
  3439. ["Enter"] = new List<string> { "'", "]", "\\", "RightShift" },
  3440. // ==============================================
  3441. // 第五行:LeftShift Z X C V B N M , . / RightShift
  3442. // ==============================================
  3443. ["LeftShift"] = new List<string> { "CapsLock", "A", "S", "D", "Z", "Ctrl", "Fn" },
  3444. ["Z"] = new List<string> { "LeftShift", "A", "S", "X" },
  3445. ["X"] = new List<string> { "Z", "S", "D", "C" },
  3446. ["C"] = new List<string> { "X", "D", "F", "V" },
  3447. ["V"] = new List<string> { "C", "F", "G", "B" },
  3448. ["B"] = new List<string> { "V", "G", "H", "N" },
  3449. ["N"] = new List<string> { "B", "H", "J", "M" },
  3450. ["M"] = new List<string> { "N", "J", "K", "," },
  3451. [","] = new List<string> { "M", "K", "L", "." },
  3452. ["."] = new List<string> { ",", "L", ";", "/" },
  3453. ["/"] = new List<string> { ".", ";", "'", "RightShift" },
  3454. ["RightShift"] = new List<string> { "/", "Enter" },
  3455. // ==============================================
  3456. // 第六行:Ctrl Fn Win Alt Space Alt Fn Ctrl ← ↓ →
  3457. // ==============================================
  3458. ["Ctrl"] = new List<string> { "Fn", "LeftShift" },
  3459. ["Fn"] = new List<string> { "Ctrl", "Win", "LeftShift" },
  3460. ["Win"] = new List<string> { "Fn", "Alt" },
  3461. ["Alt"] = new List<string> { "Win", "Space" },
  3462. ["Space"] = new List<string> { "Alt", "RightAlt" },
  3463. ["RightAlt"] = new List<string> { "Space", "RightFn" },
  3464. ["RightFn"] = new List<string> { "RightAlt", "RightCtrl" },
  3465. ["RightCtrl"] = new List<string> { "RightFn", "←", "↓", "→" },
  3466. ["←"] = new List<string> { "RightCtrl", "↓" },
  3467. ["↓"] = new List<string> { "←", "→", "RightCtrl" },
  3468. ["→"] = new List<string> { "↓", "RightCtrl" }
  3469. };
  3470. }
  3471. private async void DoYieldTime(object state)
  3472. {
  3473. try
  3474. {
  3475. //获取当前产品
  3476. CurrentProduct = _productService.GetCurrentProduct();
  3477. var currentproduct = _productService.GetCurrentProduct();
  3478. if (currentproduct == null) return;
  3479. TotalQuantity = await _systemDatabaseService.GetOverallProductionAsync(currentproduct.Name);
  3480. TotalQuantityToday = await _systemDatabaseService.GetTodayProductionAsync(currentproduct.Name);
  3481. CurrentUPH = await _systemDatabaseService.GetLastHourProductionAsync(currentproduct.Name);
  3482. NgNumber = await _systemDatabaseService.GetNGProductionAsync(currentproduct.Name);
  3483. Yield = ((double)TotalQuantityToday - (double)NgNumber) / (double)TotalQuantityToday * 100;
  3484. }
  3485. catch (Exception)
  3486. {
  3487. }
  3488. }
  3489. #region vm启动检测
  3490. /// <summary>
  3491. /// 杀死所有VM有关进程
  3492. /// </summary>
  3493. public void KillVMProcess()
  3494. {
  3495. KillProcess("VisionMasterServerApp");
  3496. KillProcess("VisionMaster");
  3497. KillProcess("VmModuleProxy.exe");
  3498. KillProcess("vServerApp.exe");
  3499. }
  3500. /// <summary>
  3501. /// 杀死指定进程名的进程
  3502. /// </summary>
  3503. /// <param name="strKillName"></param>
  3504. public void KillProcess(string strKillName)
  3505. {
  3506. foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcesses())
  3507. {
  3508. if (p.ProcessName.Contains(strKillName))
  3509. {
  3510. try
  3511. {
  3512. p.Kill();
  3513. p.WaitForExit();
  3514. }
  3515. catch (Exception ex)
  3516. {
  3517. LogHelper.WriteLogError($"杀死进程:{strKillName}时失败!", ex);
  3518. }
  3519. }
  3520. }
  3521. }
  3522. #endregion
  3523. /// <summary>
  3524. /// 记录工位的结果,其他工位要存储的数据项按照键值对集合的形式传入,键为数据项名称,值为数据项的值
  3525. /// </summary>
  3526. /// <param name="stationIndex"></param>
  3527. /// <param name="dfcs"></param>
  3528. /// <param name="productMainSN"></param>
  3529. /// <param name="ct"></param>
  3530. /// <param name="timestamp"></param>
  3531. /// <param name="savePath"></param>
  3532. /// <param name="isFirstEnter"></param>
  3533. /// <returns></returns>
  3534. private bool RecordStationResult(int stationIndex, IEnumerable<DataFormCtq> dfcs, string productMainSN, double ct, DateTime timestamp, string savePath, bool isFirstEnter = true)
  3535. {
  3536. try
  3537. {
  3538. //获取当前工位的配置
  3539. var stationConfig = _configService.GetDeviceInfo(0);
  3540. if (stationConfig == null) return false;
  3541. //如果保存路径为空,则不保存
  3542. if (string.IsNullOrEmpty(savePath)) return false;
  3543. string fullPath = savePath;
  3544. //如果保存路径是一个文件路径,则直接保存,否则按照工位和日期进行保存
  3545. if (File.Exists(savePath) || Path.HasExtension(savePath))
  3546. {
  3547. fullPath = savePath;
  3548. //如果路径不存在,则创建
  3549. // 创建目录
  3550. string directory = Path.GetDirectoryName(fullPath);
  3551. if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
  3552. {
  3553. Directory.CreateDirectory(directory);
  3554. }
  3555. }
  3556. else
  3557. {
  3558. //结果保存至CSV文件,文件名格式:savePath\yyyy-MM\工位编号_工位名称_yyyy-MM-dd.csv
  3559. string datePath = timestamp.ToString("yyyy-MM") + "\\";
  3560. string dirPath = Path.Combine(savePath, datePath);
  3561. if (!Directory.Exists(dirPath)) Directory.CreateDirectory(dirPath);
  3562. string fileName = $"{stationIndex}_{stationConfig.DeviceName}_{timestamp.ToString("yyyy-MM-dd")}.csv";
  3563. fullPath = Path.Combine(dirPath, fileName);
  3564. }
  3565. StringBuilder sb = new StringBuilder();
  3566. if (!File.Exists(fullPath))
  3567. {
  3568. 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#," +
  3569. "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");
  3570. sb.AppendLine();
  3571. }
  3572. if (dfcs == null || dfcs.Count() == 0)
  3573. {
  3574. return false;
  3575. }
  3576. foreach (var dfc in dfcs)
  3577. {
  3578. 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}");
  3579. sb.AppendLine();
  3580. }
  3581. // 使用 StreamWriter 以追加模式打开文件
  3582. StreamWriter sw = new StreamWriter(fullPath, true, Encoding.UTF8);
  3583. sw.Write(sb.ToString());
  3584. sw.Close();
  3585. sw.Dispose();
  3586. return true;
  3587. }
  3588. catch (Exception ex)
  3589. {
  3590. if (!isFirstEnter)
  3591. {
  3592. return false;
  3593. }
  3594. LogHelper.WriteLogError("记录其他工位结果时出错!", ex);
  3595. //我希望在这里生成一个临时文件来保存这次的记录,因为如果本地文件被打开时可能会导致无法写入,如果不保存的话可能会丢失这次的记录,所以我想在这里生成一个临时文件来保存这次的记录
  3596. //生成临时文件的路径,格式为savePath\yyyy-MM\工位编号_yyyy-MM-dd_temp\工位编号_yyyy-MM-dd_HH-mm-ss-fff_temp.csv
  3597. string datePath = timestamp.ToString("yyyy-MM") + "\\";
  3598. string tempDirPath = Path.Combine(savePath, datePath, $"{stationIndex}_{timestamp.ToString("yyyy-MM-dd")}_temp");
  3599. string tempFileName = $"{stationIndex}_{timestamp.ToString("yyyy-MM-dd_HH-mm-ss-fff")}_temp.csv";
  3600. RecordStationResult(stationIndex, dfcs, productMainSN, ct, timestamp, tempFileName, false);
  3601. return false;
  3602. }
  3603. }
  3604. #endregion
  3605. // 用于等待“指定相机的下一张图到达”
  3606. private readonly object _imageSyncLock = new object();
  3607. private readonly Dictionary<Guid, TaskCompletionSource<ICogImage>> _nextImageTcsByCamera =
  3608. new Dictionary<Guid, TaskCompletionSource<ICogImage>>();
  3609. private Task<ICogImage> PrepareNextImageWait(Guid cameraId)
  3610. {
  3611. lock (_imageSyncLock)
  3612. {
  3613. var tcs = new TaskCompletionSource<ICogImage>(TaskCreationOptions.RunContinuationsAsynchronously);
  3614. _nextImageTcsByCamera[cameraId] = tcs;
  3615. return tcs.Task;
  3616. }
  3617. }
  3618. public async Task SignalImageArrived(Guid cameraId, ICogImage image)
  3619. {
  3620. await Task.Delay(500);
  3621. TaskCompletionSource<ICogImage> tcs = null;
  3622. lock (_imageSyncLock)
  3623. {
  3624. _nextImageTcsByCamera.TryGetValue(cameraId, out tcs);
  3625. }
  3626. tcs?.TrySetResult(image);
  3627. }
  3628. public async Task<ICogImage> WaitNextImageAsync(Guid cameraId, int timeoutMs, CancellationToken token)
  3629. {
  3630. var waitTask = PrepareNextImageWait(cameraId);
  3631. var completed = await Task.WhenAny(waitTask, Task.Delay(timeoutMs, token)).ConfigureAwait(false);
  3632. if (completed != waitTask) return null;
  3633. return await waitTask.ConfigureAwait(false);
  3634. }
  3635. //public async Task<bool> WaitImageFlagAsync(int cameraNo, int timeoutMs, CancellationToken token)
  3636. //{
  3637. // if (cameraNo < 0 || cameraNo >= ImageData.Length)
  3638. // {
  3639. // SendTaskMessage($"等待相机图像失败:CameraNo={cameraNo} 越界", MessageLevel.Alarm);
  3640. // return false;
  3641. // }
  3642. // var start = DateTime.UtcNow;
  3643. // while (ImageData[cameraNo] == 0)
  3644. // {
  3645. // token.ThrowIfCancellationRequested();
  3646. // if ((DateTime.UtcNow - start).TotalMilliseconds >= timeoutMs)
  3647. // {
  3648. // SendTaskMessage($"等待相机图像超时:CameraNo={cameraNo} Timeout={timeoutMs}ms", MessageLevel.Alarm);
  3649. // return false;
  3650. // }
  3651. // await Task.Delay(100, token).ConfigureAwait(false);
  3652. // }
  3653. // return true;
  3654. //}
  3655. // ====== 新增:最简等待:TCS + 超时(比 SemaphoreSlim + CurrentCount 轮询更轻、更可靠)======
  3656. private async Task<string> ScanT1Async(int timeoutMs)
  3657. {
  3658. var scannerId = GetDefaultScannerId();
  3659. if (scannerId == Guid.Empty) return null;
  3660. var scanner = _scannerService.GetScanner(scannerId);
  3661. if (scanner == null || !scanner.IsConnected) return null;
  3662. // 关键:先注册等待,再发送 T1,避免“回包先到”导致丢信号
  3663. var tcs = new TaskCompletionSource<string>(TaskCreationOptions.RunContinuationsAsynchronously);
  3664. _scanTcs = tcs;
  3665. await scanner.SendAsync("T1").ConfigureAwait(false);
  3666. var completed = await Task.WhenAny(tcs.Task, Task.Delay(timeoutMs)).ConfigureAwait(false);
  3667. if (completed != tcs.Task)
  3668. {
  3669. // 超时:清掉本次等待,避免下次误用
  3670. if (ReferenceEquals(_scanTcs, tcs)) _scanTcs = null;
  3671. return null;
  3672. }
  3673. var reply = await tcs.Task.ConfigureAwait(false);
  3674. if (ReferenceEquals(_scanTcs, tcs)) _scanTcs = null;
  3675. return reply;
  3676. }
  3677. private Guid GetDefaultScannerId()
  3678. {
  3679. if (_defaultScannerId != Guid.Empty) return _defaultScannerId;
  3680. var scannerInfo = _configService.GetAllScanners()
  3681. .OrderBy(s => s.ScannerNo)
  3682. .FirstOrDefault();
  3683. _defaultScannerId = scannerInfo == null ? Guid.Empty : scannerInfo.Id;
  3684. return _defaultScannerId;
  3685. }
  3686. private async Task Scan_DataReceived(ISerialPortClient client, ReceivedDataEventArgs e)
  3687. {
  3688. try
  3689. {
  3690. // 串口名
  3691. string portName = client.MainSerialPort.PortName;
  3692. // 注意:DataReceived 可能一次收到多段/包含回车换行
  3693. string data = e.ByteBlock.Span.ToString(Encoding.ASCII);
  3694. await Console.Out.WriteLineAsync(data);
  3695. // 取第一段(到 \r 之前),并去掉首尾空白
  3696. string response = data.Split('\r')[0].Trim();
  3697. // 过滤:空数据不要当成一次有效扫码
  3698. if (string.IsNullOrWhiteSpace(response))
  3699. return;
  3700. SendTaskMessage($"扫码机:{portName} Receive:{response}", MessageLevel.Info);
  3701. // 写入结果
  3702. ScanValue = response;
  3703. // 通知等待方继续执行(PLC 逻辑里 Wait 的地方)
  3704. _scanDoneEvent.Set();
  3705. }
  3706. catch (Exception ex)
  3707. {
  3708. LogHelper.WriteLogError("扫码枪接收信息时出错!", ex);
  3709. SendTaskMessage(Lang.扫码枪接收信息时出错 + ex.Message, MessageLevel.Error);
  3710. }
  3711. }
  3712. /// <summary>
  3713. /// 2D相机先采集图像
  3714. /// </summary>
  3715. /// <param name="procedureId"></param>
  3716. /// <returns></returns>
  3717. private async Task<(bool IsSucceed, ICogImage[] imges, string Message, int pointIndex, Guid procedureId)> GrabImageEx(int pointIndex, Guid procedureId,bool Is3dPhoto)
  3718. {
  3719. // 获取当前产品
  3720. var currentProduct = _productService.GetCurrentProduct();
  3721. if (currentProduct == null)
  3722. {
  3723. return (false, null, "当前产品为空,未加载产品!", pointIndex, procedureId);
  3724. }
  3725. var cameraProcedures = currentProduct.CameraProcedures;
  3726. if (cameraProcedures == null || cameraProcedures.Count == 0)
  3727. {
  3728. SendTaskMessage($"当前产品未配置 CameraProcedures,无法执行视觉流程", MessageLevel.Alarm);
  3729. return (false, null, $"当前产品未配置 CameraProcedures,无法执行视觉流程", pointIndex, procedureId);
  3730. }
  3731. try
  3732. {
  3733. ProcedureModel selectedProcedure = null;
  3734. try
  3735. {
  3736. foreach (var cp in cameraProcedures)
  3737. {
  3738. if (cp?.ProcedureModels == null) continue;
  3739. selectedProcedure = cp.ProcedureModels.FirstOrDefault(pm => pm.Id == procedureId);
  3740. if (selectedProcedure != null) break;
  3741. }
  3742. }
  3743. catch (Exception ex)
  3744. {
  3745. LogHelper.WriteLogError("查找 AOI 点位对应视觉流程时出错", ex);
  3746. }
  3747. if (selectedProcedure == null)
  3748. {
  3749. SendTaskMessage($"未找到 AOI 点位对应的视觉流程,Point#{pointIndex} ProcedureId={pointIndex}", MessageLevel.Alarm);
  3750. return (false, null, $"未找到 AOI 点位对应的视觉流程,Point#{pointIndex} ProcedureId={procedureId}", pointIndex, procedureId);
  3751. }
  3752. SendTaskMessage($"开始执行 AOI 流程 (Point#{pointIndex}) 流程Id={pointIndex}", MessageLevel.Debug);
  3753. try
  3754. {
  3755. var sysConfig = _configService.GetSystemConfiguration();
  3756. if (selectedProcedure.Id == currentProduct.FixedDownCameraProcedureId && sysConfig.TurnOnAllLightUse == true)
  3757. {
  3758. await _remoteCommandService.SetLightBeforePhoto(selectedProcedure);
  3759. }
  3760. //1. 执行拍照
  3761. var res = await _remoteCommandService.ExecuteGrabImageAsync(selectedProcedure,Is3dPhoto);
  3762. return (res.IsSucceed, res.Image, res.Msg, pointIndex, procedureId);
  3763. }
  3764. catch (Exception ex)
  3765. {
  3766. LogHelper.WriteLogError("执行 AOI 视觉图像采集时出错", ex);
  3767. SendTaskMessage($"执行 AOI 视觉图像采集时出错: {ex.Message}", MessageLevel.Alarm);
  3768. }
  3769. return (false, null, $"图像采集失败", pointIndex, procedureId);
  3770. }
  3771. catch (Exception ex)
  3772. {
  3773. LogHelper.WriteLogError("处理固定相机检测拍照时出错", ex);
  3774. return (false, null, $"处理固定相机检测拍照时出错", pointIndex, procedureId);
  3775. }
  3776. }
  3777. #region 压缩图片文件夹
  3778. /// <summary>
  3779. /// 压缩文件
  3780. /// </summary>
  3781. /// <param name="sourcePath">原路径</param>
  3782. /// <param name="zipname">压缩后文件的名称</param>
  3783. /// <param name="station">mes中的station</param>
  3784. /// <param name="fixid">mes中的fixtureID</param>
  3785. public async void CompressionImage(string sourcePath, string zipname, string station, string fixid)
  3786. {
  3787. string zipPath = "";
  3788. try
  3789. {
  3790. SendTaskMessage($"开始压缩文件", MessageLevel.Info);
  3791. await Task.Run(() =>
  3792. {
  3793. zipPath = $"Z:\\{station}\\{fixid}\\{DateTime.Now.ToString("yyyyMMdd")}\\{zipname}.zip";//生成的zip文件路径
  3794. string path = $"Z:\\{station}\\{fixid}\\{DateTime.Now.ToString("yyyyMMdd")}";
  3795. if (!Directory.Exists(path))
  3796. {
  3797. Directory.CreateDirectory(path);
  3798. }
  3799. ZipFile.CreateFromDirectory(sourcePath, zipPath);
  3800. });
  3801. }
  3802. catch (Exception ex)
  3803. {
  3804. LogHelper.WriteLogError($"压缩文件时出错", ex);
  3805. }
  3806. }
  3807. public async void CompressionSingleCsv(string csvFilePath, string zipname, string station, string fixid)
  3808. {
  3809. string zipPath = "";
  3810. try
  3811. {
  3812. SendTaskMessage("开始压缩CSV文件", MessageLevel.Info);
  3813. await Task.Run(() =>
  3814. {
  3815. if (!File.Exists(csvFilePath))
  3816. {
  3817. LogHelper.WriteLogMes($"CSV文件不存在,不压缩:{csvFilePath}");
  3818. return;
  3819. }
  3820. zipPath = $"Z:\\{station}\\{fixid}\\{DateTime.Now.ToString("yyyyMMdd")}\\{zipname}.zip";
  3821. string path = $"Z:\\{station}\\{fixid}\\{DateTime.Now.ToString("yyyyMMdd")}";
  3822. if (!Directory.Exists(path))
  3823. {
  3824. Directory.CreateDirectory(path);
  3825. }
  3826. using (FileStream fs = new FileStream(zipPath, FileMode.Create))
  3827. {
  3828. using (ZipArchive archive = new ZipArchive(fs, ZipArchiveMode.Create))
  3829. {
  3830. archive.CreateEntryFromFile(csvFilePath, Path.GetFileName(csvFilePath));
  3831. }
  3832. }
  3833. });
  3834. SendTaskMessage("CSV文件压缩完成", MessageLevel.Debug);
  3835. }
  3836. catch (Exception ex)
  3837. {
  3838. LogHelper.WriteLogError("压缩CSV文件失败", ex);
  3839. }
  3840. }
  3841. #endregion
  3842. }
  3843. }