Management.cs 272 KB

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