Management.cs 323 KB

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