Management.cs 334 KB

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