| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575 | using System;using System.Collections.Generic;using System.Linq;using System.Diagnostics;using Aitex.Core.Common;using Aitex.Core.RT.Routine;using Aitex.Core.RT.SCCore;using Aitex.Sorter.Common;using Aitex.Core.RT.Log;using Aitex.Core.Util;using Aitex.Core.RT.DataCenter;using Aitex.Core.RT.RecipeCenter;using Aitex.Core.RT.Fsm;using MECF.Framework.Common.Jobs;using MECF.Framework.Common.Routine;using MECF.Framework.Common.Equipment;using MECF.Framework.Common.SubstrateTrackings;using MECF.Framework.Common.Schedulers;using MECF.Framework.Common.DBCore;using Venus_Core;using Venus_RT.Modules.Schedulers;using Venus_RT.Scheduler;using Venus_Unity;using MECF.Framework.RT.EquipmentLibrary.HardwareUnits.PMs;using System.Linq.Expressions;namespace Venus_RT.Modules{    public class WaferTask    {        public ModuleName           sourceMod           { get; }        public int                  sourceSlot          { get; }        public ModuleName           destMod             { get; private set; }        public int                  destSlot            { get; private set; }        public ModuleName           currentMod          { get; private set; }        public int                  currentSlot         { get; private set; }        public ModuleName           nextMod             { get; private set; }        public int                  nextSlot            { get; private set; }        public ModuleName           routedMod           { get; private set; }        public int                  routedSlot          { get; private set; }        public Hand                 hand                { get; private set; }        public SequenceLLInOutPath  llInOutPath         { get; }        public string               processRecipe       { get; }        public string               wtwCleanRecipe      { get; }        public float                temperature         { get; }        public Guid                 waferId             { get; }        public int                  elapseTime          { get { return (int)(DateTime.Now - _scheduledTime).TotalSeconds; } }        public int                  llDelayTime         { get; }        public RState               pressureStatus      { get; private set; }        public RState               temperatureStatus   { get; private set; }        public RState               movingStatus        { get; private set; }        public bool                 IsCompleted         { get { return movingStatus == RState.End && currentMod == destMod && currentSlot == destSlot; } }        public bool                 IsTimeout           { get { return elapseTime > 600; } }        public bool                 IsAligned           { get; set; }        public bool IsWaitingAtmMoving        {            get            {                if (movingStatus != RState.Init)                    return false;                return !IsWaitingVacMoving;            }        }        public bool IsWaitingVacMoving        {            get            {                if ( movingStatus == RState.Init &&                    (ModuleHelper.IsPm(nextMod) ||                     ModuleHelper.IsTMRobot(nextMod) ||                     ModuleHelper.IsPm(currentMod) ||                      ModuleHelper.IsTMRobot(currentMod)))                    return true;                return false;            }        }        public delegate void WaferMoveHandler(WaferTask wafer, MoveItem item);        public event WaferMoveHandler OnWaferArrived;        public event WaferMoveHandler OnWaferLeaved;        private DateTime _scheduledTime;        public WaferTask(ModuleName source, int srcSlot, ModuleName dest, int dstSlot, float temp, Guid waferID, string recipeName, string wtwClean, SequenceLLInOutPath inOutPath, int LLDelay, bool needAlign)        {            sourceMod = currentMod = nextMod = routedMod = source;            sourceSlot = currentSlot = nextSlot = routedSlot = srcSlot;            destMod = dest;            destSlot = dstSlot;            hand = Hand.None;            temperature = temp;            waferId = waferID;            processRecipe = recipeName;            wtwCleanRecipe = wtwClean;            llInOutPath = inOutPath;            llDelayTime = LLDelay;            IsAligned = !needAlign;            pressureStatus = RState.Init;            temperatureStatus = RState.End;            movingStatus = RState.Init;            _scheduledTime = DateTime.Now;        }        public RState Run()        {            if (movingStatus == RState.Running)            {                var wafer = WaferManager.Instance.GetWafer(nextMod, nextSlot);                if (!wafer.IsEmpty && wafer.InnerId == waferId)                {                    LOG.Write(eEvent.EV_ROUTER, ModuleName.System, $"Wafer {wafer.WaferOrigin} from  {currentMod}.{currentSlot + 1} move to {nextMod}.{nextSlot + 1}");                    if (!ModuleHelper.IsTMRobot(currentMod) && !ModuleHelper.IsEFEMRobot(currentMod))                    {                        OnWaferLeaved(this, new MoveItem(currentMod, currentSlot, nextMod, nextSlot, hand));                    }                    if (!ModuleHelper.IsTMRobot(nextMod) && !ModuleHelper.IsEFEMRobot(nextMod))                    {                        _scheduledTime = DateTime.Now;                        wafer.NextSequenceStep++;                        OnWaferArrived(this, new MoveItem(currentMod, currentSlot, nextMod, nextSlot, hand));                    }                    currentMod = nextMod;                    currentSlot = nextSlot;                    movingStatus = RState.End;                }            }            return RState.Running;        }        public void RouteTo(ModuleName mod, int slot)        {            routedMod = mod;            routedSlot = slot;            movingStatus = RState.Init;        }        public void MoveTo(ModuleName mod, int slot)        {            nextMod = mod;            nextSlot = slot;            movingStatus = RState.Running;            if(ModuleHelper.IsLoadLock(currentMod) && ModuleHelper.IsTMRobot(nextMod) && ModuleHelper.IsLoadLock(routedMod))            {                routedMod = ModuleName.TMRobot; // fix the bug which missing call RouteTo() on Vac side            }        }        public void ReAssignPM(ModuleName pm, int slot)        {            destMod = pm;             destSlot = slot;        }        public void Return()        {            destMod = sourceMod;            destSlot = sourceSlot;            movingStatus = RState.End;            pressureStatus = RState.End;            temperatureStatus = RState.End;        }    }    public enum ModuleStatus    {        Idle,        WaitMove,        Moving,        NotReady,        // PM Status        WaitProcess,        StartProcess,        Processing,        StartIdleClean,        IdleClean,        WaitPreJobClean,        StartPreJobClean,        PreJobClean,        WaitPostJobClean,        StartPostJobClean,        PostJobClean,        WaitWTWClean,        StartWTWClean,        WTWClean,        // Align Status        WaitAlign,        StartAlign,        Aligning,        // Loadlock Status        ExchangeWaferWithEFEM,        ExchangeWaferWithTM,    }    public class ModuleTask    {        public ModuleName                   Module      { get; }        public ModuleStatus                 Status      { get; set; }        public SchedulerModule              Scheduler   { get; }        public virtual int                  SlotNum     { get; protected set; }        public virtual bool                 IsIdle      { get { return Status == ModuleStatus.Idle; } }        private int     _currentActionTime = 0;        public virtual int IdleTime        {            get            {                if (Status != ModuleStatus.Idle)                    return 0;                return (int)(DateTime.Now - _moduleTimer).TotalSeconds;            }        }        public virtual int BusyTime        {            get             {                if (Status == ModuleStatus.Idle)                    return 0;                return (int)(DateTime.Now - _moduleTimer).TotalSeconds;            }        }        public virtual int BusyLastTime        {            get            {                if (Status == ModuleStatus.Idle)                    return 0;                return _currentActionTime - BusyTime;            }        }        public virtual int TimeToReady        {            get             {                 if(Scheduler.IsAvailable)                    return 0;                return int.MaxValue;            }        }        protected DateTime _moduleTimer;        public ModuleTask(ModuleName mod)        {            Module = mod;            Scheduler = Singleton<TransferModule>.Instance.GetScheduler(mod);            SlotNum = 1;            _moduleTimer = DateTime.Now;        }        public virtual RState Run()        {            Status = Scheduler.IsAvailable ? ModuleStatus.Idle : ModuleStatus.NotReady;            return RState.Running;        }        public virtual void WaferArrived(WaferTask wafer, int slot)        {        }        public virtual void WaferLeaved(WaferTask wafer, int slot)        {        }        public virtual void ResetTask()        {        }    }    public class PMTask : ModuleTask    {        enum CleanType        {            IdleClean,            PreJobClean,            PostJobClean,            WTWClean,        }        public override int TimeToReady        {            get             {                switch(Status)                {                    case ModuleStatus.Idle:                    case ModuleStatus.Processing:                    case ModuleStatus.IdleClean:                    case ModuleStatus.PreJobClean:                        {                            return Scheduler.IsAvailable ? 0 : (Scheduler.TimeToReady + 500) / 1000;                        }                    case ModuleStatus.PostJobClean:                    case ModuleStatus.WTWClean:                        {                            if(_pendingCleanTask.Count == 0)                            {                                return Scheduler.IsAvailable ? 0 : (Scheduler.TimeToReady + 500) / 1000;                            }                        }                        break;                }                return int.MaxValue;            }        }        private WaferTask _wafer;        private SchedulerPM _pmScheduler => Scheduler as SchedulerPM;        private string _preJobCleanRecipe;        private string _postJobCleanRecipe;        private string _wtwCleanRecipe;        private Queue<CleanType> _pendingCleanTask = new Queue<CleanType>();        public PMTask(ModuleName pm) : base(pm)        {        }        public override RState Run()        {            if(Scheduler.IsIdle)            {                switch (Status)                {                    case ModuleStatus.Idle:                        {                            if(WaferManager.Instance.CheckNoWafer(Module, 0) && Scheduler.IsOnline)                            {                                if (_pendingCleanTask.Count > 0)                                {                                    var cleanTask = _pendingCleanTask.Dequeue();                                    if (cleanTask == CleanType.PostJobClean && !string.IsNullOrWhiteSpace(_postJobCleanRecipe))                                    {                                        Status = ModuleStatus.WaitPostJobClean;                                    }                                    else if (cleanTask == CleanType.PreJobClean && !string.IsNullOrWhiteSpace(_preJobCleanRecipe))                                    {                                        Status = ModuleStatus.WaitPreJobClean;                                    }                                }                                else if (_pmScheduler.RunIdleCleanTask())  // Check Idle Clean                                {                                    Status = ModuleStatus.StartIdleClean;                                }                            }                        }                        break;                    case ModuleStatus.WaitProcess:                        {                            Scheduler.EventWaferArrived?.Invoke(this, new WaferMoveArgs(ModuleName.TMRobot, 0, Module, 0));                            Status = ModuleStatus.StartProcess;                        }                        break;                    case ModuleStatus.WaitPreJobClean:                        {                            if(WaferManager.Instance.CheckNoWafer(Module, 0))                            {                                if (_pmScheduler.RunJobCleanTask(_preJobCleanRecipe))                                {                                    Status = ModuleStatus.StartPreJobClean;                                }                                else                                {                                    LOG.Write(eEvent.WARN_ROUTER, Module, $"Run Prejob clean recipe{_preJobCleanRecipe} failed");                                    Status = ModuleStatus.Idle;                                    _preJobCleanRecipe = string.Empty;                                }                            }                        }                        break;                    case ModuleStatus.WaitPostJobClean:                        {                            if (WaferManager.Instance.CheckNoWafer(Module, 0))                            {                                if (_pmScheduler.RunJobCleanTask(_postJobCleanRecipe))                                {                                    Status = ModuleStatus.StartPostJobClean;                                }                                else                                {                                    LOG.Write(eEvent.WARN_ROUTER, Module, $"Run Postjob clean recipe{_postJobCleanRecipe} failed");                                    Status = ModuleStatus.Idle;                                    _postJobCleanRecipe = string.Empty;                                }                            }                        }                        break;                                        case ModuleStatus.WaitWTWClean:                        {                            if (WaferManager.Instance.CheckNoWafer(Module, 0))                            {if (_pmScheduler.RunJobCleanTask(_wtwCleanRecipe))                                {                                    Status = ModuleStatus.StartWTWClean;                                }                                else                                {                                    LOG.Write(eEvent.WARN_ROUTER, Module, $"Run WTW Wafer clean recipe{_wtwCleanRecipe} failed");                                    Status = ModuleStatus.Idle;                                    _wtwCleanRecipe = string.Empty;                                }                            }                        }                        break;                    case ModuleStatus.Processing:                        {                            var wafer = WaferManager.Instance.GetWafer(Module, 0);                            if(Scheduler.IsOnline)                            {                                if (!wafer.IsEmpty && wafer.ProcessState == EnumWaferProcessStatus.Completed)                                {                                    _wafer.Return();                                    Status = ModuleStatus.Idle;                                }                            }                            else  // handle offline exception situation                            {                                Status = ModuleStatus.Idle;                            }                        }                        break;                    case ModuleStatus.PreJobClean:                        {                            _preJobCleanRecipe = string.Empty;                            Status = ModuleStatus.Idle;                        }                        break;                    case ModuleStatus.PostJobClean:                        {                            _postJobCleanRecipe = string.Empty;                            if (_pendingCleanTask.Count > 0)                            {                                var cleanTask = _pendingCleanTask.Dequeue();                                if(cleanTask == CleanType.PreJobClean && !string.IsNullOrWhiteSpace(_preJobCleanRecipe))                                {                                    Status = ModuleStatus.WaitPreJobClean;                                    break;                                }                            }                            Status = ModuleStatus.Idle;                        }                        break;                    case ModuleStatus.WTWClean:                        {                            if(_pendingCleanTask.Count > 0)                            {                                var cleanTask = _pendingCleanTask.Dequeue();                                if (cleanTask == CleanType.PostJobClean && !string.IsNullOrWhiteSpace(_postJobCleanRecipe))                                {                                    Status = ModuleStatus.WaitPostJobClean;                                }                                else if (cleanTask == CleanType.PreJobClean && !string.IsNullOrWhiteSpace(_preJobCleanRecipe))                                {                                    Status = ModuleStatus.WaitPreJobClean;                                }                            }                            else                            {                                Status = ModuleStatus.Idle;                            }                            _wtwCleanRecipe = string.Empty;                        }                        break;                    case ModuleStatus.IdleClean:                        {                            Status = ModuleStatus.Idle;                         }                        break;                    case ModuleStatus.StartProcess:                        {                            if(RouteManager.IsATMMode)                            {                                Status = ModuleStatus.Processing;                            }                        }                        break;                }            }            else            {                switch(Status)                {                    case ModuleStatus.StartProcess:                        Status = ModuleStatus.Processing;                        break;                    case ModuleStatus.StartIdleClean:                        Status = ModuleStatus.IdleClean;                        break;                    case ModuleStatus.StartPreJobClean:                        Status = ModuleStatus.PreJobClean;                        break;                    case ModuleStatus.StartPostJobClean:                        Status = ModuleStatus.PostJobClean;                        break;                    case ModuleStatus.StartWTWClean:                        Status = ModuleStatus.WTWClean;                        break;                }            }            return RState.Running;        }        public override void WaferArrived(WaferTask wafer, int slot)        {            _wafer = wafer;            Status = ModuleStatus.WaitProcess;        }        public override void WaferLeaved(WaferTask wafer, int slot)        {            if(!string.IsNullOrWhiteSpace(_wafer.wtwCleanRecipe.Trim()))            {                Status = ModuleStatus.WaitWTWClean;                _wtwCleanRecipe = _wafer.wtwCleanRecipe;            }            else if(_pendingCleanTask.Count > 0)            {                var cleanTask = _pendingCleanTask.Dequeue();                if (cleanTask == CleanType.PostJobClean && !string.IsNullOrWhiteSpace(_postJobCleanRecipe))                {                    Status = ModuleStatus.WaitPostJobClean;                }                else if (cleanTask ==  CleanType.PreJobClean && !string.IsNullOrWhiteSpace(_preJobCleanRecipe))                {                    Status = ModuleStatus.WaitPreJobClean;                }            }            _wafer = null;        }        public void InvokePreJobClean(string preJobClean)        {            _preJobCleanRecipe = preJobClean;            _pendingCleanTask.Enqueue(CleanType.PreJobClean);        }        public bool IsPreJobCleanDone()        {            return !_pendingCleanTask.Contains(CleanType.PreJobClean) && string.IsNullOrWhiteSpace(_preJobCleanRecipe);        }        public void InvokePostJobClean(string postJobClean)        {            _postJobCleanRecipe = postJobClean;            _pendingCleanTask.Enqueue(CleanType.PostJobClean);        }        public bool IsPostJobCleanDone()        {            return !_pendingCleanTask.Contains(CleanType.PostJobClean) && string.IsNullOrWhiteSpace(_postJobCleanRecipe);        }    }    public class AlignerTask : ModuleTask    {        private WaferTask _wafer;        public AlignerTask(ModuleName aligner) : base(aligner)        {        }        public override RState Run()        {            var efemRobot = Singleton<TransferModule>.Instance.GetScheduler(ModuleName.EfemRobot) as SchedulerEfemRobot;            if (efemRobot == null || !efemRobot.IsAvailable)                return RState.Running;            switch (Status)            {                case ModuleStatus.WaitAlign:                    {                                                efemRobot.Align(0);                        Status = ModuleStatus.Aligning;                    }                    break;                case ModuleStatus.Aligning:                    {                        _wafer.IsAligned = true;                        Status = ModuleStatus.Idle;                    }                    break;            }            return RState.Running;        }        public override void WaferArrived(WaferTask wafer, int slot)        {            _wafer = wafer;            Status = ModuleStatus.WaitAlign;        }        public override void WaferLeaved(WaferTask wafer, int slot)        {            _wafer = null;        }    }    public class LoadPortTask : ModuleTask    {        public LoadPortTask(ModuleName lp) : base(lp)        {            SlotNum = SC.GetValue<int>($"EFEM.LoadPort.SlotNumber");        }        public override RState Run()        {            return base.Run();        }    }    public class TMRobotTask : ModuleTask    {        public TMRobotTask(ModuleName tmRobot) : base(tmRobot)        {            SlotNum = 2;        }        public override RState Run()        {            return base.Run();        }    }    public class EFEMRobotTask : ModuleTask    {        public EFEMRobotTask(ModuleName efemRobot) : base(efemRobot)        {            SlotNum = 2;        }        public override RState Run()        {            return base.Run();        }        public bool PostMoveItems(MoveItem[] items)        {            Status = ModuleStatus.Moving;            return (Scheduler as SchedulerEfemRobot).PostMoveItems(items);        }    }    public class LoadlockTask : ModuleTask    {        private Dictionary<int, int> _wafersDelayTime = new Dictionary<int, int>();        public LoadlockTask(ModuleName ll) : base(ll)        {            SlotNum = SC.GetValue<int>($"{ll}.SlotNumber");            for (int slot = 0; slot < SlotNum; slot++)                _wafersDelayTime[slot] = -1;        }        public override int TimeToReady        {            get { return Scheduler.IsAvailable ? 0 : (Scheduler.TimeToReady + 500) / 1000; }        }        public int ReayOutWafersInTime(int seconds)        {            int readyOut = 0;            foreach(var slot in _wafersDelayTime)            {                if (slot.Value >= 0 && Scheduler.WaferArrivedTicks(slot.Key) / 1000 + seconds > slot.Value)                    readyOut++;            }            return readyOut;        }        public override void WaferArrived(WaferTask wafer, int slot)        {            Scheduler.WaferArrived(slot);            if(ModuleHelper.IsLoadPort(wafer.destMod))            {                _wafersDelayTime[slot] = wafer.llDelayTime;            }            else            {                _wafersDelayTime[slot] = -1;            }        }        public override void WaferLeaved(WaferTask wafer, int slot)        {            _wafersDelayTime[slot] = -1;        }        public bool PreVent()        {            if (Scheduler.IsAvailable && Scheduler.IsVac)            {                return (Scheduler as SchedulerLoadLock).PreVent();            }            return false;        }        public bool PrePump()        {            if (Scheduler.IsAvailable && Scheduler.IsAtm)            {                return (Scheduler as SchedulerLoadLock).PrePump();            }            return false;        }    }    enum LLSlotInOutOpt    {        AllInAllOut,        UpperInLowerOut,        LowerInUpperOut,    }    class SystemDispatcher : ICycle    {        private List<ControlJobInfo> _lstControlJobs = new List<ControlJobInfo>();        private List<ProcessJobInfo> _lstProcessJobs = new List<ProcessJobInfo>();        private List<WaferTask> _lstWaferTasks = new List<WaferTask>();        private Dictionary<ModuleName, ModuleTask> _dictModuleTask = new Dictionary<ModuleName, ModuleTask>();        private Queue<WaferInfo> _qeReturnWafers = new Queue<WaferInfo>();        private Queue<List<MoveItem>> _efemSchdActions = new Queue<List<MoveItem>>();        private Queue<List<MoveItem>> _tmSchdActions = new Queue<List<MoveItem>>();        private List<MoveItem> _curEfemAction = new List<MoveItem>();        private List<MoveItem> _curTmAction = new List<MoveItem>();                private RState _efemRobotStatus { get { return (_dictModuleTask[ModuleName.EfemRobot].Scheduler as SchedulerEfemRobot).RobotStatus; } }        private RState _tmRobotStatus { get { return (_dictModuleTask[ModuleName.TMRobot].Scheduler as SchedulerTMRobot).RobotStatus; } }        private SchedulerFACallback _faCallback;        private SchedulerDBCallback _dbCallback;        private readonly int _LLASlotNumber = 4;        private readonly int _LLBSlotNumber = 4;        private int _efemRobotSingleArmOption = 0;        private int _tmRobotSingleArmOption = 0;        private LLSlotInOutOpt _LLSlotInOutOption = 0;        private Dictionary<ModuleName, int> _lpCycleWafer = new Dictionary<ModuleName, int> { { ModuleName.LP1, 0},  { ModuleName.LP2, 0 },{ ModuleName.LP3, 0 } };        private Dictionary<ModuleName, int> _lpCycleCount = new Dictionary<ModuleName, int> { { ModuleName.LP1, 0 }, { ModuleName.LP2, 0 }, { ModuleName.LP3, 0 } };        private Dictionary<ModuleName, int> _lpCycleSP    = new Dictionary<ModuleName, int> { { ModuleName.LP1, 1 }, { ModuleName.LP2, 1 }, { ModuleName.LP3, 1 } };        private Dictionary<ModuleName, float> _lpThroughput = new Dictionary<ModuleName, float> { { ModuleName.LP1, 0 }, { ModuleName.LP2, 0 }, { ModuleName.LP3, 0 } };        private Stopwatch _cycleWatch = new Stopwatch();        private SequenceLLInOutPath _LLInOutPath = SequenceLLInOutPath.DInDOut;        public SequenceLLInOutPath LLInOutPath => _LLInOutPath;         public bool HasJobRunning => _lstControlJobs.Count > 0;        private RState _cycleState = RState.Init;        public RState CycleState => _cycleState;        private Dictionary<string, ControlJobInfo> _loadportControlJobDic = new Dictionary<string, ControlJobInfo>();        public List<string> InUseRecipes = new List<string>();        #region public interface        public SystemDispatcher()        {            _faCallback = new SchedulerFACallback();            _dbCallback = new SchedulerDBCallback();            _efemRobotSingleArmOption = SC.GetValue<int>("EFEM.SingleArmOption");            _tmRobotSingleArmOption = SC.GetValue<int>("TM.SingleArmOption");            _LLASlotNumber = SC.GetValue<int>("LLA.SlotNumber");            _LLBSlotNumber = SC.GetValue<int>("LLB.SlotNumber");            InitModules();            DATA.Subscribe("Scheduler.PjIdList", () => Array.ConvertAll(_lstProcessJobs.ToArray(), x => x.InnerId.ToString()).ToList());            DATA.Subscribe("Scheduler.PjNameList", () => Array.ConvertAll(_lstProcessJobs.ToArray(), x => x.LotName.ToString()).ToList());            DATA.Subscribe("Scheduler.InUsingRecipe", () => InUseRecipes);            foreach (var lp in new List<ModuleName> { ModuleName.LP1, ModuleName.LP2, ModuleName.LP3})            {                _loadportControlJobDic[lp.ToString()] = null;                DATA.Subscribe($"{lp}.CurrentControlJob", () => _loadportControlJobDic[lp.ToString()], SubscriptionAttribute.FLAG.IgnoreSaveDB);                DATA.Subscribe($"{lp}.CycledCount",   () => _lpCycleCount.Keys.Contains(lp) ?_lpCycleCount[lp]:0, SubscriptionAttribute.FLAG.IgnoreSaveDB);                DATA.Subscribe($"{lp}.CycledWafer",   () => _lpCycleCount.Keys.Contains(lp) ? _lpCycleWafer[lp]:0, SubscriptionAttribute.FLAG.IgnoreSaveDB);                DATA.Subscribe($"{lp}.CycleSetPoint", () => _lpCycleCount.Keys.Contains(lp) ? _lpCycleSP[lp]:0, SubscriptionAttribute.FLAG.IgnoreSaveDB);                DATA.Subscribe($"{lp}.Throughput",    () => _lpCycleCount.Keys.Contains(lp) ? _lpThroughput[lp]:0, SubscriptionAttribute.FLAG.IgnoreSaveDB);            }        }        /// <summary>        /// 获取lp当前的ControlJob        /// </summary>        /// <param name="lp"></param>        /// <returns></returns>        public ControlJobInfo GetLoadPortCurrentControlJob(ModuleName lp)        {            if(ModuleHelper.IsLoadPort(lp))            {                return _loadportControlJobDic.ContainsKey(lp.ToString()) ? _loadportControlJobDic[lp.ToString()] : null;            }            else            {                return null;             }        }        public RState Start(params object[] objs)        {            if(WaferManager.Instance.HasDuplicatedWafer)            {                LOG.Write(eEvent.ERR_ROUTER, ModuleName.System, "System has dummy wafers, please verify all the wafer position, and delete the invalid wafer");                return RState.Failed;            }            _efemRobotSingleArmOption   = SC.GetValue<int>("EFEM.SingleArmOption");            _tmRobotSingleArmOption     = SC.GetValue<int>("TM.SingleArmOption");            _LLSlotInOutOption          = (LLSlotInOutOpt)SC.GetValue<int>("System.LoadlockSlotInOutOption");            // rounding TM robot single arm option            if(_tmRobotSingleArmOption > 2 && _LLSlotInOutOption == LLSlotInOutOpt.AllInAllOut)            {                _tmRobotSingleArmOption = 0;            }            _cycleWatch.Stop();            _lpCycleWafer.Clear();            _lpCycleCount.Clear();            return RState.Running;        }        public RState Monitor()        {            prelude();            RunWaferTask();            RunModuleTasks();            RoutingATMWafers();            RoutingVacWafers();                       epilogue();            return _cycleState;        }        public void Abort()        {        }        public bool CreateJob(Dictionary<string, object> param, out string reason)        {            reason = "";            string[] slotSequence = (string[])param["SlotSequence"];            string jobId = (string)param["JobId"];            string module = (string)param["Module"];            if (string.IsNullOrEmpty(jobId))            {                jobId = "CJ_Local_" + module;            }            //bool autoStart        = (bool)param["AutoStart"];            string lotId = jobId;            if (param.ContainsKey("LotId"))                lotId = (string)param["LotId"];            string preCleanRecipe = param.ContainsKey("PreCleanRecipeName") ? (string)param["PreCleanRecipeName"] : string.Empty;            string postCleanRecipe = param.ContainsKey("PostCleanRecipeName") ? (string)param["PostCleanRecipeName"] : string.Empty;            int cycleNumber= param.ContainsKey("CycleNumber") ? (int)param["CycleNumber"] : 1;            if (slotSequence.Length != SC.GetValue<int>("EFEM.LoadPort.SlotNumber"))            {                reason = $"slot sequence parameter not valid, length is {slotSequence.Length}, should be {SC.GetValue<int>("EFEM.LoadPort.SlotNumber")}";                LOG.Write(eEvent.WARN_ROUTER, ModuleName.System, reason);                _faCallback.JobCreateFailed(module, lotId, jobId, "");                return false;            }            if (!ModuleHelper.IsLoadPort(ModuleHelper.Converter(module)))            {                reason = $"{module} should be LoadPort";                LOG.Write(eEvent.WARN_ROUTER, ModuleName.System, reason);                _faCallback.JobCreateFailed(module, lotId, jobId, "");                return false;            }            if (_lstControlJobs.Exists(x => x.Name == jobId))            {                reason = $"{jobId} already created";                LOG.Write(eEvent.WARN_ROUTER, ModuleName.System, reason);                _faCallback.JobCreateFailed(module, lotId, jobId, "");                return false;            }            ControlJobInfo cj = new ControlJobInfo();            cj.Name = jobId;            cj.Module = module;            cj.LotName = lotId;            cj.LotInnerId = Guid.NewGuid();            cj.LotWafers = new List<WaferInfo>();            cj.SetState(EnumControlJobState.WaitingForStart);            cj.JetState = EnumJetCtrlJobState.Created;            cj.PreJobClean = preCleanRecipe;            cj.PostJobClean = postCleanRecipe;            cj.SequenceNameList = slotSequence;            cj.CycleNumber = cycleNumber; // only for temperary debug            _lpCycleSP[ModuleHelper.Converter(module)] = cj.CycleNumber;            Dictionary<string, bool[]> seqSlot = new Dictionary<string, bool[]>();            Dictionary<string, List<Tuple<ModuleName, int>>> seqSlotWafers = new Dictionary<string, List<Tuple<ModuleName, int>>>();            Dictionary<string, string> indexSequence = new Dictionary<string, string>();            bool enableGroupBySequence = SC.GetValue<bool>("Scheduler.GroupWaferBySequence");            for (int i = 0; i < SC.GetValue<int>("EFEM.LoadPort.SlotNumber"); i++)            {                if (string.IsNullOrEmpty(slotSequence[i]) || string.IsNullOrEmpty(slotSequence[i].Trim()))                    continue;                string groupName = enableGroupBySequence ? slotSequence[i].Trim() : i.ToString();                indexSequence[groupName] = slotSequence[i];                if (!seqSlot.ContainsKey(groupName))                {                    seqSlot[groupName] = new bool[SC.GetValue<int>("EFEM.LoadPort.SlotNumber")];                }                if (!seqSlotWafers.ContainsKey(groupName))                {                    seqSlotWafers[groupName] = new List<Tuple<ModuleName, int>>();                }                seqSlot[groupName][i] = true;                if (!WaferManager.Instance.CheckHasWafer(module, i))                {                    LOG.Write(eEvent.WARN_ROUTER, ModuleName.System, $"job wafer: {module} slot {i + 1} not in the carrier");                    return false;                }                if (!WaferManager.Instance.CheckWafer(ModuleHelper.Converter(module), i, WaferStatus.Normal))                {                    reason = $"job wafer: {module} slot {i + 1} status is {WaferManager.Instance.GetWafer(ModuleHelper.Converter(module), i).Status}";                    LOG.Write(eEvent.WARN_ROUTER, ModuleName.System, reason);                    _faCallback.JobCreateFailed(module, lotId, jobId, "");                    return false;                }                if (WaferManager.Instance.GetWafer(ModuleHelper.Converter(module), i).ProcessState != EnumWaferProcessStatus.Idle)                {                    reason = $"job wafer: {module} slot {i + 1} process status is {WaferManager.Instance.GetWafer(ModuleHelper.Converter(module), i).ProcessState}";                    LOG.Write(eEvent.WARN_ROUTER, ModuleName.System, reason);                    _faCallback.JobCreateFailed(module, lotId, jobId, "");                    return false;                }                //--- 2024-03-21 增加了waferinfo 相应的lotId信息 start---                WaferInfo waferInfo = WaferManager.Instance.GetWafer(ModuleHelper.Converter(module), i);                cj.LotWafers.Add(waferInfo);                waferInfo.SequenceName = slotSequence[i];                waferInfo.LotId = lotId;                //--- 2024-03-21 增加了waferinfo 相应的lotId信息 end---                seqSlotWafers[groupName].Add(Tuple.Create(ModuleHelper.Converter(module), i));                cj.JobWaferSize = WaferManager.Instance.GetWafer(ModuleHelper.Converter(module), i).Size;                LOG.Write(eEvent.EV_ROUTER, ModuleName.System, $"Assigned wafer job, wafer {module}.{i + 1}, sequence: {slotSequence[i]}");            }            if (seqSlotWafers.Count == 0)            {                reason = $"job has not assign wafer";                LOG.Write(eEvent.WARN_ROUTER, ModuleName.System, reason);                _faCallback.JobCreateFailed(module, lotId, jobId, "");                return false;            }            List<ProcessJobInfo> pjs = new List<ProcessJobInfo>();            string[] seqs = seqSlot.Keys.ToArray();            for (int i = 0; i < seqs.Length; i++)            {                ProcessJobInfo pj = new ProcessJobInfo();                pj.Name = jobId + "_" + (i + 1);                pj.Sequence = SequenceInfoHelper.GetInfo(indexSequence[seqs[i]]);                if (pj.Sequence == null)                {                    reason = $"invalid sequence[{indexSequence[seqs[i]]}]";                    return false;                }                pj.ControlJobName = cj.Name;                pj.LotName = lotId;                pj.SlotWafers = seqSlotWafers[seqs[i]];                pj.SetState(EnumProcessJobState.Queued);                if (!CheckSequencePmReady(pj.Sequence, out reason))                {                    LOG.Write(eEvent.WARN_ROUTER, ModuleName.System, $"no valid chamber for the {reason}");                    _faCallback.JobCreateFailed(module, lotId, jobId, "");                    return false;                }                if (!RouteManager.IsATMMode && !CheckSequenceRecipeFileValid(pj.Sequence, out reason))                {                    LOG.Write(eEvent.WARN_ROUTER, ModuleName.System, $"recipe file not valid in the sequence, {reason}");                    _faCallback.JobCreateFailed(module, lotId, jobId, "");                    return false;                }                pjs.Add(pj);            }            _dbCallback.LotUpdate(cj);            foreach (var pj in pjs)            {                cj.ProcessJobNameList.Add(pj.Name);                _lstProcessJobs.Add(pj);            }            _lstControlJobs.Add(cj);            //AssociatedPMWithLP(cj);            _loadportControlJobDic[cj.Module] = cj;            _faCallback.JobCreated(cj, GetFirstProcessJob(cj));            return true;        }        public bool CheckAllJobDone()        {            foreach (var cj in _lstControlJobs)            {                if (cj.State == EnumControlJobState.Executing || cj.State == EnumControlJobState.Paused)                    return false;            }            InUseRecipes.Clear();            return true;        }        public bool CheckJobJustDone(out string sJobName)        {            foreach (var cj in _lstControlJobs)            {                if (cj.State == EnumControlJobState.Completed && !cj.BeenPosted)                {                    //LP;WaferSize;Lot;Number;Start;End;                    sJobName = $"{cj.Module};{cj.JobWaferSize};{cj.LotName};{cj.LotWafers.Count};{cj.StartTime:T};{cj.EndTime:T}";                    cj.BeenPosted = true;                    return true;                }            }            sJobName = "NULL";            return false;        }        public ProcessJobInfo GetFirstProcessJob(ControlJobInfo cj)        {            foreach (var pj in _lstProcessJobs)            {                if (pj.ControlJobName == cj.Name)                    return pj;            }            return null;        }        public bool AbortJob(string jobName, out string reason)        {            reason = "";            ControlJobInfo cj = _lstControlJobs.Find(x => x.Name == jobName);            if (cj == null)            {                reason = $"abort job rejected, not found job with id {jobName}";                LOG.Write(eEvent.WARN_ROUTER, ModuleName.System, reason);                return false;            }            List<ProcessJobInfo> pjAbortList = new List<ProcessJobInfo>();            foreach (var pj in _lstProcessJobs)            {                if (pj.ControlJobName == cj.Name)                {                    pj.SetState(EnumProcessJobState.Aborting);                    pjAbortList.Add(pj);                    int unprocessed = 0;                    int aborted = 0;                    WaferInfo[] wafers = WaferManager.Instance.GetWaferByProcessJob(pj.Name);                    foreach (var waferInfo in wafers)                    {                        waferInfo.ProcessJob = null;                        waferInfo.NextSequenceStep = 0;                        if (waferInfo.ProcessState != EnumWaferProcessStatus.Completed)                            unprocessed++;                    }                    JobDataRecorder.EndPJ(pj.InnerId.ToString(), aborted, unprocessed);                }            }            _faCallback.JobAborted(cj, GetFirstProcessJob(cj));            _dbCallback.LotFinished(cj);            foreach (var pj in pjAbortList)            {                _lstProcessJobs.Remove(pj);            }            _lstControlJobs.Remove(cj);            if (_loadportControlJobDic.ContainsKey(cj.Module))            {                _loadportControlJobDic[cj.Module] = null;            }            return true;        }        public bool StopJob(string jobName, out string reason)        {            reason = "";            ControlJobInfo cj = _lstControlJobs.Find(x => x.Name == jobName);            if (cj == null)            {                reason = $"stop job rejected, not found job with id {jobName}";                LOG.Write(eEvent.WARN_ROUTER, ModuleName.System, reason);                return false;            }            foreach (var pj in _lstProcessJobs)            {                if (pj.ControlJobName == cj.Name)                {                    pj.SetState(EnumProcessJobState.Stopping);                }            }            _faCallback.JobStopped(cj, GetFirstProcessJob(cj));            _dbCallback.LotFinished(cj);            if (_loadportControlJobDic.ContainsKey(cj.Module))            {                _loadportControlJobDic[cj.Module] = null;            }            return true;        }        public bool ResumeJob(string jobName, out string reason)        {            reason = "";            ControlJobInfo cj = _lstControlJobs.Find(x => x.Name == jobName);            if (cj == null)            {                reason = $"resume job rejected, not found job with id {jobName}";                //LOG.Write(eEvent.WARN_ROUTER, ModuleName.System, $"resume job rejected, not found job with id {jobName}");                return false;            }            if (cj.State == EnumControlJobState.Paused)            {                cj.SetState(EnumControlJobState.Executing);            }            _faCallback.JobResumed(cj, GetFirstProcessJob(cj));            _cycleState = RState.Running;            return true;        }        public bool PauseJob(string jobName, out string reason)        {            reason = "";            ControlJobInfo cj = _lstControlJobs.Find(x => x.Name == jobName);            if (cj == null)            {                reason = $"pause job rejected, not found job with id {jobName}";                //LOG.Write(eEvent.WARN_ROUTER, ModuleName.System, $"pause job rejected, not found job with id {jobName}");                return false;            }            if (cj.State == EnumControlJobState.Executing)            {                cj.SetState(EnumControlJobState.Paused);            }            _faCallback.JobPaused(cj, GetFirstProcessJob(cj));            if (!_lstControlJobs.Exists(job => job.State == EnumControlJobState.Executing))                _cycleState = RState.Paused;            return true;        }        public bool StartJob(string jobName, out string reason)        {            reason = "";            ControlJobInfo cj = _lstControlJobs.Find(x => x.Name == jobName);            if (cj == null)            {                reason = $"start job rejected, not found job with id {jobName}";                LOG.Write(eEvent.WARN_ROUTER, ModuleName.System, reason);                return false;            }            if (RtInstance.ConfigType == ConfigType.Kepler2200)            {                foreach (var item in _lstProcessJobs)                {                    if (item.ControlJobName == cj.Name && !CheckSequenceKepler2200TemperatureReady(item.Sequence))                    {                        return false;                    }                    GetAllJobRecipe(cj, item.Sequence);                }            }            if (cj.State == EnumControlJobState.WaitingForStart)            {                cj.SetState(EnumControlJobState.Executing);                //PreJobClean(cj);                cj.JetState = EnumJetCtrlJobState.Quequed;                cj.StartTime = DateTime.Now;                _dbCallback.LotCreated(cj);                _faCallback.JobStarted(cj, GetFirstProcessJob(cj));                //if (!_blockingWatcher.IsRunning)                //    _blockingWatcher.Restart();                //ResetTraceFlag();            }            if (!_cycleWatch.IsRunning)            {                _cycleWatch.Restart();            }            if (!_lpCycleWafer.Keys.Contains(ModuleHelper.Converter(cj.Module)))            {                _lpCycleCount.Add(ModuleHelper.Converter(cj.Module), 0);                _lpCycleWafer.Add(ModuleHelper.Converter(cj.Module), 0);            }            _cycleState = RState.Running;            return true;        }        public void Clear()        {            foreach (var module in _dictModuleTask)            {                module.Value.Status = ModuleStatus.Idle;                module.Value.Scheduler.ResetTask();            }            List<string> keys = _loadportControlJobDic.Keys.ToList();            foreach (var key in keys)            {                _loadportControlJobDic[key] = null;            }            _lstWaferTasks.Clear();            _tmSchdActions.Clear();            _curTmAction.Clear();            _efemSchdActions.Clear();            _curEfemAction.Clear();            _lstControlJobs.Clear();            _lstProcessJobs.Clear();            InUseRecipes.Clear();            _cycleState = RState.End;        }        // manual return one wafer while system is auto running        public bool ManualReturnWafer(object[] objs)        {            ModuleName SourceModule = (ModuleName)objs[0];            int SourceSlot = (int)objs[1];            if (!_dictModuleTask.Keys.Contains(SourceModule))            {                LOG.Write(eEvent.WARN_ROUTER, ModuleName.System, $"Invalid source module {SourceModule} for manual return wafer");                return false;            }            if (WaferManager.Instance.CheckNoWafer(SourceModule, SourceSlot))            {                LOG.Write(eEvent.WARN_ROUTER, ModuleName.System, $"Can not return wafer as {SourceModule} {SourceSlot} has no wafer");                return false;            }            if (!_dictModuleTask[SourceModule].Scheduler.IsIdle)            {                LOG.Write(eEvent.WARN_ROUTER, ModuleName.System, $"The module: {SourceModule} is not ready for return wafer");                return false;            }            var wafer = WaferManager.Instance.GetWafer(SourceModule, SourceSlot);            LOG.Write(eEvent.EV_ROUTER, ModuleName.System, $"Manual return  wafer: {wafer.WaferOrigin} at {SourceModule} {SourceSlot} while system is auto running");            _qeReturnWafers.Enqueue(wafer);            return true;        }        public RState CheckManualReturnWafer()        {            var pmWaferCount = _dictModuleTask.Where(mod => ModuleHelper.IsPm(mod.Key) && WaferManager.Instance.CheckHasWafer(mod.Key, 0)).Count();            var tmRobotWaferCount = (WaferManager.Instance.CheckHasWafer(ModuleName.TMRobot, 0) ? 1 : 0) + (WaferManager.Instance.CheckHasWafer(ModuleName.TMRobot, 1) ? 1 : 0);            if (!_dictModuleTask[ModuleName.TMRobot].Scheduler.IsIdle && (pmWaferCount > 0 || tmRobotWaferCount > 0))            {                LOG.Write(eEvent.ERR_ROUTER, ModuleName.TMRobot, $"The TM Robot is not ready for return wafer.");                return RState.Failed;            }            if (!_dictModuleTask[ModuleName.EfemRobot].Scheduler.IsIdle)            {                LOG.Write(eEvent.ERR_ROUTER, ModuleName.EfemRobot, $"The EFEM Robot is not ready for return wafer.");                return RState.Failed;            }            foreach (var mod in _dictModuleTask)            {                if (ModuleHelper.IsLoadPort(mod.Key))                    continue;                if (!mod.Value.Scheduler.IsInclude)                    continue;                if (!mod.Value.Scheduler.IsIdle)                {                    LOG.Write(eEvent.ERR_ROUTER, mod.Key, $"{mod.Key} is not ready for return wafer.");                    return RState.Failed;                }                int nSlotNumber = ModuleHelper.IsLoadLock(mod.Key) ? (mod.Key == ModuleName.LLA ? _LLASlotNumber : _LLBSlotNumber) : (ModuleHelper.IsTMRobot(mod.Key) || ModuleHelper.IsEFEMRobot(mod.Key) ? 2 : 1);                for (int slot = 0; slot < nSlotNumber; slot++)                {                    var wafer = WaferManager.Instance.GetWafer(mod.Key, slot);                    if (wafer.IsEmpty)                        continue;                    var destLP = (ModuleName)wafer.OriginStation;                    if (!_dictModuleTask[destLP].Scheduler.IsAvailable)                    {                        LOG.Write(eEvent.ERR_ROUTER, destLP, $"The destination Loadport {destLP} is not ready for return wafer.");                        return RState.Failed;                    }                    if(!ModuleHelper.IsLoadPort(destLP))                    {                        LOG.Write(eEvent.ERR_ROUTER, ModuleName.System, $"The wafer {wafer.WaferOrigin} cannot be return, please manually drag it.");                        return RState.Failed;                    }                }            }            Clear();            return RState.Running;        }        public RState ReturnAllWafers()        {            int systemWaferCount = 0;            foreach (var mod in _dictModuleTask)            {                if (ModuleHelper.IsLoadPort(mod.Key) || !mod.Value.Scheduler.IsInclude)                    continue;                int nSlotNumber = ModuleHelper.IsLoadLock(mod.Key) ? (mod.Key == ModuleName.LLA ? _LLASlotNumber : _LLBSlotNumber) : (ModuleHelper.IsTMRobot(mod.Key) || ModuleHelper.IsEFEMRobot(mod.Key) ? 2 : 1);                for (int slot = 0; slot < nSlotNumber; slot++)                {                    var wafer = WaferManager.Instance.GetWafer(mod.Key, slot);                    if (!wafer.IsEmpty)                        systemWaferCount++;                }            }            if (systemWaferCount == 0)                return RState.End;            ReturnVacWafers();            ReturnAtmWafers();            return RState.Running;        }        #endregion        #region internal implementation        private void InitModules()        {            foreach (var module in ModuleHelper.InstalledModules)            {                if (ModuleHelper.IsInstalled(module))                {                    if(ModuleHelper.IsPm(module))                    {                        _dictModuleTask[module] = new PMTask(module);                    }                    else if (ModuleHelper.IsLoadLock(module))                    {                        _dictModuleTask[module] = new LoadlockTask(module);                    }                    else if(ModuleHelper.IsLoadPort(module))                    {                        _dictModuleTask[module] = new LoadPortTask(module);                    }                    else if(ModuleHelper.IsTMRobot(module))                    {                        _dictModuleTask[module] = new TMRobotTask(module);                    }                    else if(ModuleHelper.IsEFEMRobot(module))                    {                        _dictModuleTask[module] = new EFEMRobotTask(module);                    }                    else if(ModuleHelper.IsAligner(module))                    {                        _dictModuleTask[module] = new AlignerTask(module);                    }                }            }        }        private void prelude()        {            bool available = true;            foreach(var mod in _dictModuleTask)            {                available = mod.Value.Scheduler.IsAvailable; // force scheduler update            }        }        private void epilogue()        {            UpdateProcessJobStatus();            UpdateControlJobStatus();            UpdateLLInOutPathProperty();            PrepareLLPressure();            CreateNewWaferTask();            _lstWaferTasks.RemoveAll(item => ModuleHelper.IsLoadPort(item.destMod) && ModuleHelper.IsLoadPort(item.currentMod) && item.pressureStatus == RState.End);            ReDispatchBlockingWafers();        }        private void RunWaferTask()        {            foreach (var task in _lstWaferTasks)            {                task.Run();            }        }        private void RunModuleTasks()        {            foreach (var task in _dictModuleTask)            {                task.Value.Run();            }        }        private bool CheckAllWaferReturned(ProcessJobInfo pj, bool checkAllProcessed)        {            bool allWaferReturn = true;            foreach (var slot in pj.SlotWafers)            {                var wafer = WaferManager.Instance.GetWafer(slot.Item1, slot.Item2);                if(wafer.IsEmpty || (wafer.ProcessState != EnumWaferProcessStatus.Completed && checkAllProcessed))                {                    allWaferReturn = false;                    break;                }            }            return allWaferReturn;        }        private void UpdateProcessJobStatus()        {            if (_efemRobotStatus == RState.Running || _tmRobotStatus == RState.Running)                return;            foreach (var pj in _lstProcessJobs)            {                if (CheckAllWaferReturned(pj, pj.State != EnumProcessJobState.Stopping))                {                    pj.SetState(EnumProcessJobState.ProcessingComplete);                    JobDataRecorder.EndPJ(pj.InnerId.ToString(), 0, 0);                }            }        }        private bool IsControlJobIntersect(ControlJobInfo cj1, ControlJobInfo cj2)        {            var cj1Pms = GetWaitPreCleanPMsByCtrlJob(cj1);            var cj2Pms = GetWaitPreCleanPMsByCtrlJob(cj2);            return cj1Pms.Intersect(cj2Pms).Count() > 0;        }        private void UpdateControlJobStatus()        {            if (_lstControlJobs.Count == 0 || _efemRobotStatus == RState.Running || _tmRobotStatus == RState.Running)                return;            var runningJobs = _lstControlJobs.FindAll(cj => IsCtrlJobRuning(cj));            var queueJobs = _lstControlJobs.FindAll(cj => cj.JetState == EnumJetCtrlJobState.Quequed).OrderBy(cj => cj.StartTime);            if (runningJobs.Count == 0)            {                if(queueJobs.Count() > 0)                {                    // start the first waiting job                    RunControlJob(queueJobs.First());                }            }            else            {                foreach(var runningjob in runningJobs)                {                    // update the running job                    RunControlJob(runningjob);                }                foreach(var queueJob in queueJobs)                {                    if(!runningJobs.Exists(cj => IsControlJobIntersect(cj, queueJob)))                    {                        // parallelly start the not intersect job                        RunControlJob(queueJob);                    }                }            }            // update system cycle status            if (_lstControlJobs.All(cj => cj.State == EnumControlJobState.Completed))                _cycleState = RState.End;            List<ControlJobInfo> cjRemoveList = new List<ControlJobInfo>();            foreach (var cj in _lstControlJobs)            {                LoadportCassetteState state = (LoadportCassetteState)DATA.Poll($"{cj.Module}.CassetteState");                if (cj.State == EnumControlJobState.Completed && state != LoadportCassetteState.Normal)                {                    cjRemoveList.Add(cj);                }            }            foreach (var cj in cjRemoveList)            {                List<ProcessJobInfo> pjRemoveList = new List<ProcessJobInfo>();                foreach (var pj in _lstProcessJobs)                {                    if (pj.ControlJobName == cj.Name)                        pjRemoveList.Add(pj);                }                                foreach (var pj in pjRemoveList)                {                    _lstProcessJobs.Remove(pj);                }                _lstControlJobs.Remove(cj);            }        }        private bool ActiveProcessJob(ProcessJobInfo pj)        {            foreach (var pjSlotWafer in pj.SlotWafers)            {                WaferInfo wafer = WaferManager.Instance.GetWafer(pjSlotWafer.Item1, pjSlotWafer.Item2);                wafer.ProcessJob = pj;                wafer.NextSequenceStep = 0;                WaferDataRecorder.SetPjInfo(wafer.InnerId.ToString(), pj.InnerId.ToString());            }            ControlJobInfo cj = _lstControlJobs.Find(x => x.Name == pj.ControlJobName);            CarrierInfo carrier = CarrierManager.Instance.GetCarrier(cj.Module);            JobDataRecorder.StartPJ(pj.InnerId.ToString(), carrier.InnerId.ToString(), cj.InnerId.ToString(), pj.Name, cj.Module, cj.Module, pj.SlotWafers.Count);            pj.SetState(EnumProcessJobState.Processing);            return true;        }        private bool ActiveControlJob(ControlJobInfo cj)        {            cj.JetState = EnumJetCtrlJobState.Processing;            foreach (var pjName in cj.ProcessJobNameList)            {                var pj = _lstProcessJobs.Find(x => x.Name == pjName);                if (pj == null)                {                    LOG.Write(eEvent.ERR_ROUTER, ModuleName.System, $"Not find pj named {pjName} in {cj.Name}");                    continue;                }                if (pj.State == EnumProcessJobState.Queued)                {                    ActiveProcessJob(pj);                }            }            return true;        }        private bool RunControlJob(ControlJobInfo cj)        {            switch(cj.JetState)            {                case EnumJetCtrlJobState.Quequed:                    {                        if(IsCtrlJobNeedPreClean(cj))                        {                            cj.JetState = EnumJetCtrlJobState.PreJobClean;                            var PMs = GetWaitPreCleanPMsByCtrlJob(cj);                            foreach (var pm in PMs)                            {                                var pmTask = _dictModuleTask[pm] as PMTask;                                if (pmTask != null && pmTask.Scheduler.IsOnline)                                {                                    pmTask.InvokePreJobClean(cj.PreJobClean);                                }                            }                        }                        else                        {                            ActiveControlJob(cj);                        }                    }                    break;                case EnumJetCtrlJobState.PreJobClean:                    {                        if (IsPreJobCleanDone(cj))                        {                            ActiveControlJob(cj);                        }                    }                    break;                case EnumJetCtrlJobState.Processing:                    {                        if (IsCtrlJobNeedPostClean(cj))                        {                            if (IsAllJobWaferProcessedOrProcessing(cj))                            {                                cj.JetState = EnumJetCtrlJobState.PostJobClean;                                var PMs = GetWaitPreCleanPMsByCtrlJob(cj);                                foreach (var pm in PMs)                                {                                    var pmTask = _dictModuleTask[pm] as PMTask;                                    if (pmTask != null && pmTask.Scheduler.IsOnline)                                    {                                        pmTask.InvokePostJobClean(cj.PostJobClean);                                    }                                }                            }                        }                        else                        {                            if (IsAllProcessJobComplete(cj))                            {                                cj.JetState = EnumJetCtrlJobState.Completed;                            }                        }                    }                    break;                case EnumJetCtrlJobState.PostJobClean:                    {                        if (IsPostJobCleanDone(cj))                        {                            cj.JetState = EnumJetCtrlJobState.Completed;                        }                    }                    break;            }            // caculate processed wafer by control job            var lp = ModuleHelper.Converter(cj.Module);            int countProcessed = 0;            foreach (var pjName in cj.ProcessJobNameList)            {                var pj = _lstProcessJobs.Find(x => x.Name == pjName);                if (pj == null)                {                    LOG.Write(eEvent.ERR_ROUTER, ModuleName.System, $"Not find pj named {pjName} in {cj.Name}");                    continue;                }                // caculate process wafer by process                if (_lpCycleCount[lp] < cj.CycleNumber)                {                    foreach (var pjSlotWafer in pj.SlotWafers)                    {                        WaferInfo wafer = WaferManager.Instance.GetWafer(pjSlotWafer.Item1, pjSlotWafer.Item2);                        if (!wafer.IsEmpty && wafer.ProcessState == EnumWaferProcessStatus.Completed)                            countProcessed++;                    }                }            }            int lpCycleWafer = 0;            if (cj.JetState == EnumJetCtrlJobState.Completed)            {                cj.EndTime = DateTime.Now;                _faCallback.JobFinished(cj, GetFirstProcessJob(cj));                _dbCallback.LotFinished(cj);                if (_lpCycleCount[lp] >= cj.CycleNumber)                    (Singleton<TransferModule>.Instance.GetScheduler(lp) as SchedulerLoadPort).NoteJobComplete();                _lpCycleCount[lp]++;                lpCycleWafer = _lpCycleCount[lp] * cj.LotWafers.Count;                _lpThroughput[lp] = (float)(lpCycleWafer / (DateTime.Now - cj.StartTime).TotalHours);                LOG.Write(eEvent.EV_ROUTER, lp, $"Cycle Count: {_lpCycleCount[lp]}, Total Processed Wafer: {lpCycleWafer}, Throughput: {_lpThroughput[lp]}");                if (_lpCycleCount[lp] < cj.CycleNumber)                {                    cj.SetState(EnumControlJobState.Executing);                    cj.JetState = EnumJetCtrlJobState.Quequed;                    cj.LotInnerId = Guid.NewGuid();                    _dbCallback.LotCreated(cj);                    foreach (var pj in _lstProcessJobs)                    {                        if(pj.ControlJobName == cj.Name)                        {                            pj.SetState(EnumProcessJobState.Queued);                            pj.InnerId = Guid.NewGuid();                            foreach (var pjSlotWafer in pj.SlotWafers)                            {                                WaferInfo wafer = WaferManager.Instance.GetWafer(pjSlotWafer.Item1, pjSlotWafer.Item2);                                wafer.ProcessJob = null;                                wafer.NextSequenceStep = 0;                                wafer.ProcessState = EnumWaferProcessStatus.Idle;                            }                        }                    }                    _lstWaferTasks.RemoveAll(wt => wt.currentMod == lp);                }                else                {                    cj.SetState(EnumControlJobState.Completed);                }            }            else            {                lpCycleWafer = _lpCycleCount[lp] * cj.LotWafers.Count + countProcessed;            }            if (lpCycleWafer != _lpCycleWafer[lp])            {                _lpCycleWafer[lp] = lpCycleWafer;                if(_lpCycleCount[lp] > 0)                {                    _lpThroughput[lp] = (float)(lpCycleWafer /(DateTime.Now - cj.StartTime).TotalHours);                }            }            return cj.State == EnumControlJobState.Completed;        }        private bool IsAllJobWaferProcessedOrProcessing(ControlJobInfo cj)        {            List<ModuleName> allModules = _dictModuleTask.Keys.ToList();            int original = (int)ModuleHelper.Converter(cj.Module);            foreach (var mod in allModules)            {                if (ModuleHelper.IsLoadPort(mod) && (int)mod != original)                    continue;                var wafers = WaferManager.Instance.GetWafers(mod);                foreach (var wafer in wafers)                {                    if (wafer.IsEmpty || wafer.ProcessJob == null || wafer.ProcessJob.Sequence == null || wafer.ProcessJob.ControlJobName != cj.Name)                        continue;                    if (wafer.ProcessState != EnumWaferProcessStatus.Completed && wafer.ProcessState != EnumWaferProcessStatus.InProcess)                        return false; ;                }            }            return true;        }        private bool IsAllProcessJobComplete(ControlJobInfo cj)        {            foreach (var pj in _lstProcessJobs)            {                if (pj.ControlJobName == cj.Name && pj.State != EnumProcessJobState.ProcessingComplete)                {                    return false;                }            }            return true;        }        private bool IsCtrlJobExecuting(ModuleName lp)        {            var cJob = _lstControlJobs.Find(cj => ModuleHelper.Converter(cj.Module) == lp);            if (cJob != null && cJob.State == EnumControlJobState.Executing)                return true;            return false;        }        private bool IsCtrlJobRuning(ControlJobInfo cj)        {            return cj.JetState == EnumJetCtrlJobState.PreJobClean ||                cj.JetState == EnumJetCtrlJobState.Processing ||                cj.JetState == EnumJetCtrlJobState.PostJobClean;        }        private bool IsCtrlJobEndingState(ControlJobInfo cj)        {            return cj.JetState == EnumJetCtrlJobState.PostJobClean ||                (cj.JetState == EnumJetCtrlJobState.Processing                && IsAllJobWaferProcessedOrProcessing(cj)                && !IsCtrlJobNeedPostClean(cj));        }        private bool IsCtrlJobNeedPreClean(ControlJobInfo cj)        {            return !string.IsNullOrWhiteSpace(cj.PreJobClean);        }        private bool IsCtrlJobNeedPostClean(ControlJobInfo cj)        {            return !string.IsNullOrWhiteSpace(cj.PostJobClean.Trim());        }        private List<ModuleName> GetWaitPreCleanPMsByCtrlJob(ControlJobInfo cj)        {            var pmlist = new List<ModuleName>();            foreach (var pj in _lstProcessJobs)            {                if (pj.ControlJobName == cj.Name)                {                    foreach (var pm in pj.Sequence.PMs)                    {                        if (!pmlist.Contains(pm))                            pmlist.Add(pm);                    }                }            }            return pmlist;        }        private bool IsPreJobCleanDone(ControlJobInfo cj)        {            var pms = GetWaitPreCleanPMsByCtrlJob(cj);            foreach(var pm in pms)            {                var pmTask = _dictModuleTask[pm] as PMTask;                if (pmTask.Scheduler.IsOnline && !pmTask.IsPreJobCleanDone())                    return false;            }            return true;        }        private bool IsPostJobCleanDone(ControlJobInfo cj)        {            var pms = GetWaitPreCleanPMsByCtrlJob(cj);            foreach (var pm in pms)            {                var pmTask = _dictModuleTask[pm] as PMTask;                if (pmTask.Scheduler.IsOnline && !pmTask.IsPostJobCleanDone())                    return false;            }            return true;        }        private void WaferArrived(WaferTask wafer, MoveItem item)        {            _dictModuleTask[item.DestinationModule].WaferArrived(wafer, item.DestinationSlot);            //--2024-03-21 增加了PortJobWaferEnd 上报事件 start--            if (ModuleHelper.IsLoadPort(item.DestinationModule))            {                ControlJobInfo currentControlJob = GetLoadPortCurrentControlJob(item.DestinationModule);                if (currentControlJob != null)                {                    _faCallback.JobWaferEnd(currentControlJob, item.SourceSlot);                }            }            //--2024-03-21 增加了PortJobWaferEnd 上报事件 end--        }        private void WaferLeaved(WaferTask wafer, MoveItem item)        {            _dictModuleTask[item.SourceModule].WaferLeaved(wafer, item.DestinationSlot);            //--2024-03-21 增加了PortJobWaferStart 上报事件 start--            if (ModuleHelper.IsLoadPort(item.SourceModule))            {                ControlJobInfo currentControlJob = GetLoadPortCurrentControlJob(item.SourceModule);                if (currentControlJob != null)                {                    _faCallback.JobWaferStart(currentControlJob, item.SourceSlot);                }            }            //--2024-03-21 增加了PortJobWaferStart 上报事件 end--        }        private ModuleName GetComingAvailablePM(ControlJobInfo cj)        {            var lstInProcessPMs = new List<ModuleName>();            foreach (var wafer in cj.LotWafers)            {                if(!wafer.IsEmpty && wafer.NextSequenceStep == 0 && wafer.ProcessJob != null)                {                    foreach(var pm in wafer.ProcessJob.Sequence.PMs)                    {                        if (!lstInProcessPMs.Contains(pm) && _dictModuleTask[pm].Scheduler.IsOnline)                            lstInProcessPMs.Add(pm);                    }                }            }            // blocking check while only one loadlock in out            if (LLInOutPath == SequenceLLInOutPath.AInAOut ||                 LLInOutPath == SequenceLLInOutPath.BInBOut ||                 !_dictModuleTask[ModuleName.LLA].Scheduler.IsOnline ||                 !_dictModuleTask[ModuleName.LLB].Scheduler.IsOnline)            {                if (_lstWaferTasks.Count >= lstInProcessPMs.Count + _LLASlotNumber / 2)                    return ModuleName.System;            }            Dictionary<ModuleName, int> pmAssociatedWaferCount = new Dictionary<ModuleName, int>();            foreach (var mod in _dictModuleTask)            {                if (ModuleHelper.IsPm(mod.Key) && mod.Value.Scheduler.IsOnline && lstInProcessPMs.Contains(mod.Key))                {                    pmAssociatedWaferCount[mod.Key] = 0;                }            }            var unprocessedWafer = _lstWaferTasks.Where(task => ModuleHelper.IsPm(task.destMod));            foreach (var wafer in unprocessedWafer)            {                if (ModuleHelper.IsPm(wafer.destMod) && _dictModuleTask[wafer.destMod].Scheduler.IsOnline && lstInProcessPMs.Contains(wafer.destMod))                {                    pmAssociatedWaferCount[wafer.destMod]++;                }            }            var oderedPMCount = pmAssociatedWaferCount.OrderBy(p => p.Value).ToDictionary(p => p.Key, o => o.Value);            if (oderedPMCount.Count > 0 && oderedPMCount.First().Value < 2)                return oderedPMCount.First().Key;            return ModuleName.System;        }        private void CreateNewWaferTask()        {            var runningJobs = _lstControlJobs.FindAll(cj => cj.JetState == EnumJetCtrlJobState.PreJobClean || cj.JetState == EnumJetCtrlJobState.Processing);            var onDutyPms = new Dictionary<ModuleName, int>();            foreach (var job in runningJobs)             {                var pms = GetWaitPreCleanPMsByCtrlJob(job);                foreach(var pm in pms)                {                    if (_dictModuleTask[pm].Scheduler.IsOnline && !onDutyPms.ContainsKey(pm))                    {                        onDutyPms[pm] = _lstWaferTasks.Where(wt => wt.destMod == pm).Count();                    }                }            }            if (runningJobs.Count == 0 || onDutyPms.Count == 0)                return;            var oderedPMs = onDutyPms.OrderBy(kv => kv.Value).OrderBy(kv => _dictModuleTask[kv.Key].TimeToReady);            if(oderedPMs.First().Value < 1)            {                foreach(var runningJob in runningJobs)                {                    foreach (var wafer in runningJob.LotWafers)                    {                        if (wafer.IsEmpty || wafer.ProcessJob == null)                            continue;                        if (wafer.ProcessJob.Sequence.PMs.Contains(oderedPMs.First().Key) && wafer.NextSequenceStep == 0 && !_lstWaferTasks.Exists(task => task.sourceMod == (ModuleName)wafer.OriginStation && task.sourceSlot == wafer.OriginSlot))                        {                            CreateWaferTasks(wafer, oderedPMs.First().Key);                            return;                        }                    }                }            }        }        private void CreateWaferTasks(WaferInfo wafer, ModuleName pm)        {            var recipeName = wafer.ProcessJob.Sequence.GetRecipe(pm);            var recipeContent = RecipeFileManager.Instance.LoadRecipe(pm.ToString(), recipeName, false, RecipeType.Process.ToString());            Recipe recipe = Recipe.Load(recipeContent);            int temperature = 0;            if(int.TryParse(recipe.Header.Temperature, out int temp))            {                temperature = temp;            }            var waferTask = new WaferTask((ModuleName)wafer.OriginStation,                                            wafer.OriginSlot,                                            pm,                                            0,                                            temperature,                                            wafer.InnerId,                                            recipeName,                                            wafer.ProcessJob.Sequence.WTWCleanRecipe,                                            wafer.ProcessJob.Sequence.LLInOutPath,                                             wafer.ProcessJob.Sequence.LLDelayTime,                                            IsSequenceNeedAlign(wafer.ProcessJob.Sequence));            waferTask.OnWaferArrived += WaferArrived;            waferTask.OnWaferLeaved += WaferLeaved;            _lstWaferTasks.Add(waferTask);        }        private void ReDispatchBlockingWafers()        {            foreach (var wt in _lstWaferTasks)            {                if (ModuleHelper.IsPm(wt.destMod) && !ModuleHelper.IsPm(wt.currentMod) && !ModuleHelper.IsLoadPort(wt.currentMod))                {                    if (!_dictModuleTask[wt.destMod].Scheduler.IsOnline && wt.elapseTime > 120)                    {                        var wafer = WaferManager.Instance.GetWafer(wt.currentMod, wt.currentSlot);                        var otherPMs = _dictModuleTask.Where(mod => wafer.ProcessJob.Sequence.PMs.Contains(mod.Key) && mod.Value.Scheduler.IsOnline).OrderBy(mod => _lstWaferTasks.Where(task => task.destMod == mod.Key).Count()).ToList();                        if(otherPMs.Count > 0)                        {                            LOG.Write(eEvent.WARN_ROUTER, wt.currentMod, $"Re-assign process chamber {otherPMs.First().Key} for {wafer.WaferOrigin} as {wt.destMod} unexpected offline");                            wt.ReAssignPM(otherPMs.First().Key, 0);                        }                    }                }            }        }        private bool ForwardATMWafers(ModuleName ll)        {            var emptySlots = _LLSlotInOutOption == LLSlotInOutOpt.AllInAllOut ? GetLLReadyInOutSlots(ll).emptySlot : GetLLFixedReadyInOutSlots(ll).eInSlot;            var atmWafers = _lstWaferTasks.Where(wafer => (wafer.movingStatus == RState.End ||wafer.movingStatus == RState.Init) && (ModuleHelper.IsEFEMRobot(wafer.currentMod) || ModuleHelper.IsAligner(wafer.currentMod))).ToList();            var notAlignedWafer = atmWafers.Where(wafer => !wafer.IsAligned).ToList();            var readyInWafers = _lstWaferTasks.Where(wafer => ModuleHelper.IsLoadPort(wafer.currentMod) && IsCtrlJobExecuting(wafer.currentMod) && wafer.movingStatus == RState.Init && wafer.pressureStatus == RState.Init && CanWaferGotoLL(wafer, ll)).OrderBy(wafer => wafer.currentSlot).ToArray();            var freeHands = GetEFEMFreeHand();            if ((atmWafers.Count >= 2 && !atmWafers.Exists(wafer => !wafer.IsAligned)) || freeHands.Count == 0 || readyInWafers.Length == 0)                return false;            // force all wafer aligned            if (notAlignedWafer.Count > 0 && _lstWaferTasks.Count(wafer => ModuleHelper.IsAligner(wafer.currentMod)) == 0)            {                notAlignedWafer.First().RouteTo(ModuleName.Aligner1, 0);                _efemSchdActions.Enqueue(new List<MoveItem> { new MoveItem(notAlignedWafer.First().currentMod, notAlignedWafer.First().currentSlot, ModuleName.Aligner1, 0, (Hand)notAlignedWafer.First().currentSlot) });            }            // forward aligner wafer            else if (atmWafers.Count == 1 && emptySlots.Count >= 2 && ModuleHelper.IsAligner(atmWafers.First().currentMod) && freeHands.Count > 1)            {                atmWafers.First().RouteTo(ModuleName.EfemRobot, (int)freeHands[1]);                _efemSchdActions.Enqueue(new List<MoveItem> { new MoveItem(atmWafers.First().currentMod, atmWafers.First().currentSlot, ModuleName.EfemRobot, (int)freeHands[1], freeHands[1]) });            }            // forward one wafer            else if ((readyInWafers.Length > 0) && (atmWafers.Count == 0 || (atmWafers.Count == 1 && emptySlots.Count >= 2)))            {                if(readyInWafers[0].IsAligned)                {                    // pick from LP                    _efemSchdActions.Enqueue(new List<MoveItem> { new MoveItem(readyInWafers[0].currentMod, readyInWafers[0].currentSlot, ModuleName.EfemRobot, (int)freeHands[0], freeHands[0]) });                }                else if(!_lstWaferTasks.Exists(wt => ModuleHelper.IsAligner(wt.currentMod)))                {                    readyInWafers[0].RouteTo(ModuleName.Aligner1, 0);                    // pick from LP                    _efemSchdActions.Enqueue(new List<MoveItem> { new MoveItem(readyInWafers[0].currentMod, readyInWafers[0].currentSlot, ModuleName.EfemRobot, (int)freeHands[0], freeHands[0]) });                    // place to aligner                    _efemSchdActions.Enqueue(new List<MoveItem> { new MoveItem(ModuleName.EfemRobot, (int)freeHands[0], ModuleName.Aligner1, 0, freeHands[0]) });                }            }            return _efemSchdActions.Count > 0;        }        private bool ExchangeWaferWithLL(ModuleName ll)        {            if (IsLLReservedByTM(ll))                return false;            var waferStaus = GetLLReadyInOutSlots(ll);            var atmWafers = _lstWaferTasks.Where(wafer => (wafer.movingStatus == RState.End || wafer.movingStatus == RState.Init) && wafer.IsAligned && (ModuleHelper.IsEFEMRobot(wafer.currentMod) || ModuleHelper.IsAligner(wafer.currentMod))).ToList();            var freeHands = GetEFEMFreeHand();            var swapActions = new List<MoveItem>();            var validHands = new List<Hand>();            int placeCount = 0;            if ( waferStaus.emptySlot.Count > 0 &&                  freeHands.Count >= 1 &&                  atmWafers.Count(wafer => ModuleHelper.IsAligner(wafer.currentMod)) == 1 &&                 (atmWafers.Count(wafer => ModuleHelper.IsEFEMRobot(wafer.currentMod)) == 0 || waferStaus.emptySlot.Count >= 2))            {                var alignerWafer = atmWafers.Where(wafer => ModuleHelper.IsAligner(wafer.currentMod)).First();                if (CanWaferGotoLL(alignerWafer, ll))                {                    alignerWafer.RouteTo(ll, waferStaus.emptySlot[placeCount]);                    _efemSchdActions.Enqueue(new List<MoveItem> { new MoveItem(alignerWafer.currentMod, alignerWafer.currentSlot, ModuleName.EfemRobot, (int)freeHands[0], freeHands[0]) });                    swapActions.Add(new MoveItem(ModuleName.EfemRobot, (int)freeHands[0], ll, waferStaus.emptySlot[placeCount], freeHands[0]));                    validHands.Add(freeHands[0]);                    placeCount++;                }            }            var armWafers = atmWafers.Where(wafer => ModuleHelper.IsEFEMRobot(wafer.currentMod)).ToArray();            foreach(var wafer in armWafers)            {                if (CanWaferGotoLL(wafer, ll) && placeCount < waferStaus.emptySlot.Count)                {                    wafer.RouteTo(ll, waferStaus.emptySlot[placeCount]);                    swapActions.Add(new MoveItem(wafer.currentMod, wafer.currentSlot, ll, waferStaus.emptySlot[placeCount], (Hand)wafer.currentSlot));                    if(!validHands.Contains((Hand)wafer.currentSlot))                        validHands.Add((Hand)wafer.currentSlot);                                             placeCount++;                }            }            if (!validHands.Contains(Hand.Blade1) && WaferManager.Instance.CheckNoWafer(ModuleName.EfemRobot, (int)Hand.Blade1) && _efemRobotSingleArmOption != 2)                validHands.Add(Hand.Blade1);            if (!validHands.Contains(Hand.Blade2) && WaferManager.Instance.CheckNoWafer(ModuleName.EfemRobot, (int)Hand.Blade2) && _efemRobotSingleArmOption != 1)                validHands.Add(Hand.Blade2);            int pickCount = 0;            var returnActions = new List<MoveItem>();            foreach(var slot in waferStaus.outSlot)            {                if(pickCount < validHands.Count)                {                    var outWafer = _lstWaferTasks.Find(wafer => (wafer.movingStatus == RState.End || wafer.movingStatus == RState.Init) && wafer.currentMod == ll && wafer.currentSlot == slot);                    if(outWafer != null)                    {                        outWafer.RouteTo(outWafer.destMod, outWafer.destSlot);                        swapActions.Add(new MoveItem(ll, waferStaus.outSlot[pickCount], ModuleName.EfemRobot, (int)validHands[pickCount], validHands[pickCount]));                        returnActions.Add(new MoveItem(ModuleName.EfemRobot, (int)validHands[pickCount], outWafer.destMod, outWafer.destSlot, validHands[pickCount]));                        pickCount++;                    }                }            }                        if(swapActions.Count > 0)            {                _efemSchdActions.Enqueue(swapActions);            }            foreach(var action in returnActions)            {                _efemSchdActions.Enqueue(new List<MoveItem> { action });            }            return _efemSchdActions.Count > 0;        }        private bool ExchangeWaferWithFixedSlotLL(ModuleName ll)        {            if (IsLLReservedByTM(ll))                return false;            var llWaferStatus = GetLLFixedReadyInOutSlots(ll);            var atmWafers = _lstWaferTasks.Where(wafer => (wafer.movingStatus == RState.End || wafer.movingStatus == RState.Init) && wafer.IsAligned && (ModuleHelper.IsEFEMRobot(wafer.currentMod) || ModuleHelper.IsAligner(wafer.currentMod))).ToList();            var freeHands = GetEFEMFreeHand();            var swapActions = new List<MoveItem>();            var validHands = new List<Hand>();            int placeCount = 0;            if (llWaferStatus.eInSlot.Count > 0 &&                 freeHands.Count >= 1 &&                 atmWafers.Count(wafer => ModuleHelper.IsAligner(wafer.currentMod)) == 1 &&                (atmWafers.Count(wafer => ModuleHelper.IsEFEMRobot(wafer.currentMod)) == 0 || llWaferStatus.eInSlot.Count >= 2))            {                var alignerWafer = atmWafers.Where(wafer => ModuleHelper.IsAligner(wafer.currentMod)).First();                if (CanWaferGotoLL(alignerWafer, ll))                {                    alignerWafer.RouteTo(ll, llWaferStatus.eInSlot[placeCount]);                    _efemSchdActions.Enqueue(new List<MoveItem> { new MoveItem(alignerWafer.currentMod, alignerWafer.currentSlot, ModuleName.EfemRobot, (int)freeHands[0], freeHands[0]) });                    swapActions.Add(new MoveItem(ModuleName.EfemRobot, (int)freeHands[0], ll, llWaferStatus.eInSlot[placeCount], freeHands[0]));                    validHands.Add(freeHands[0]);                    placeCount++;                }            }            var armWafers = atmWafers.Where(wafer => ModuleHelper.IsEFEMRobot(wafer.currentMod)).ToArray();            foreach (var wafer in armWafers)            {                if (CanWaferGotoLL(wafer, ll) && placeCount < llWaferStatus.eInSlot.Count)                {                    wafer.RouteTo(ll, llWaferStatus.eInSlot[placeCount]);                    swapActions.Add(new MoveItem(wafer.currentMod, wafer.currentSlot, ll, llWaferStatus.eInSlot[placeCount], (Hand)wafer.currentSlot));                    if (!validHands.Contains((Hand)wafer.currentSlot))                        validHands.Add((Hand)wafer.currentSlot);                    placeCount++;                }            }            if (!validHands.Contains(Hand.Blade1) && WaferManager.Instance.CheckNoWafer(ModuleName.EfemRobot, (int)Hand.Blade1) && _efemRobotSingleArmOption != 2)                validHands.Add(Hand.Blade1);            if (!validHands.Contains(Hand.Blade2) && WaferManager.Instance.CheckNoWafer(ModuleName.EfemRobot, (int)Hand.Blade2) && _efemRobotSingleArmOption != 1)                validHands.Add(Hand.Blade2);            int pickCount = 0;            var returnActions = new List<MoveItem>();            foreach (var slot in llWaferStatus.eOutSlot)            {                if (pickCount < validHands.Count)                {                    var outWafer = _lstWaferTasks.Find(wafer => (wafer.movingStatus == RState.End || wafer.movingStatus == RState.Init) && wafer.currentMod == ll && wafer.currentSlot == slot);                    if (outWafer != null)                    {                        outWafer.RouteTo(outWafer.destMod, outWafer.destSlot);                        swapActions.Add(new MoveItem(ll, llWaferStatus.eOutSlot[pickCount], ModuleName.EfemRobot, (int)validHands[pickCount], validHands[pickCount]));                        returnActions.Add(new MoveItem(ModuleName.EfemRobot, (int)validHands[pickCount], outWafer.destMod, outWafer.destSlot, validHands[pickCount]));                        pickCount++;                    }                }            }            if (swapActions.Count > 0)            {                _efemSchdActions.Enqueue(swapActions);            }            foreach (var action in returnActions)            {                _efemSchdActions.Enqueue(new List<MoveItem> { action });            }            return _efemSchdActions.Count > 0;        }        private void RoutingATMWafers()        {            if (_efemSchdActions.Count > 0 || _curEfemAction.Count > 0)            {                RunSchdEFEMActions();                return;            }            if (_efemRobotStatus != RState.End)                return;            if(_LLSlotInOutOption == LLSlotInOutOpt.AllInAllOut)            {                if (_LLASlotNumber == 2)                {                    Routing2SlotATMSystem();                }                else if (_LLASlotNumber == 4)                {                    Routing4SlotATMSystem();                }            }            else            {                RoutingFixedSlotATMSystem();            }        }        private void Routing4SlotATMSystem()        {            var atmWaferCount = _lstWaferTasks.Where(wafer => ModuleHelper.IsEFEMRobot(wafer.currentMod) || ModuleHelper.IsAligner(wafer.currentMod)).Count();            var efemRobotWafers = _lstWaferTasks.Where(wafer => ModuleHelper.IsEFEMRobot(wafer.currentMod)).ToList();            if (LLInOutPath == SequenceLLInOutPath.AInBOut || LLInOutPath == SequenceLLInOutPath.BInAOut) // don need  check system wafer existence as no blocking risk             {                var inLL = LLInOutPath == SequenceLLInOutPath.AInBOut ? ModuleName.LLA : ModuleName.LLB;                var outLL = LLInOutPath == SequenceLLInOutPath.AInBOut ? ModuleName.LLB : ModuleName.LLA;                var inLLWaferStatus = GetLLReadyInOutSlots(inLL);                var outLLWaferStatus = GetLLReadyInOutSlots(outLL);                if (efemRobotWafers.Count() >= 1)                {                    if (inLLWaferStatus.emptySlot.Count >= 2 && !IsLLReservedByTM(inLL)) // wait for in loadlock ready                    {                        if (_dictModuleTask[inLL].TimeToReady < 2)                        {                            ExchangeWaferWithLL(inLL);                        }                    }                    if ((inLLWaferStatus.emptySlot.Count == 0 || (outLLWaferStatus.outSlot.Count >= 1 && _dictModuleTask[outLL].TimeToReady < 2)) && !IsLLReservedByTM(outLL)) // ready return wafer                    {                        ExchangeWaferWithLL(outLL);                    }                }                else                {                    if (((outLLWaferStatus.outSlot.Count >= 2 && _dictModuleTask[outLL].TimeToReady < 10) ||                        (outLLWaferStatus.outSlot.Count == 1 && _dictModuleTask[outLL].TimeToReady < 2)) && !IsLLReservedByTM(outLL))                    {                        ExchangeWaferWithLL(outLL);                    }                    else if (inLLWaferStatus.emptySlot.Count >= 2)                    {                        if (((_dictModuleTask[inLL].TimeToReady > 20 || _dictModuleTask[inLL].Scheduler.IsVac) && atmWaferCount < 2) || atmWaferCount == 0)                        {                            ForwardATMWafers(inLL);                        }                        else if (atmWaferCount >= 2 && !IsLLReservedByTM(inLL))                        {                            ExchangeWaferWithLL(inLL);                        }                    }                }            }            else            {                RoutingSameLLInOutATMSystem();            }        }        private void Routing2SlotATMSystem()        {            var atmWaferCount = _lstWaferTasks.Where(wafer => ModuleHelper.IsEFEMRobot(wafer.currentMod) || ModuleHelper.IsAligner(wafer.currentMod)).Count();            var efemRobotWafers = _lstWaferTasks.Where(wafer => ModuleHelper.IsEFEMRobot(wafer.currentMod)).ToList();            var validHands = (_efemRobotSingleArmOption == 0 ? 2 : 1);            if (LLInOutPath == SequenceLLInOutPath.AInBOut || LLInOutPath == SequenceLLInOutPath.BInAOut) // don need  check system wafer existence as no blocking risk             {                var inLL = LLInOutPath == SequenceLLInOutPath.AInBOut ? ModuleName.LLA : ModuleName.LLB;                var outLL = LLInOutPath == SequenceLLInOutPath.AInBOut ? ModuleName.LLB : ModuleName.LLA;                var inLLWaferStatus = GetLLReadyInOutSlots(inLL);                var outLLWaferStatus = GetLLReadyInOutSlots(outLL);                // whether can do double return in 5 second, single return with single arm option or LL under atm pressure                if ((outLLWaferStatus.outSlot.Count == 2 && _dictModuleTask[outLL].TimeToReady < 5 && (atmWaferCount < 2 || !_dictModuleTask[outLL].Scheduler.IsAtm)) ||                     (outLLWaferStatus.outSlot.Count == 1 && ((_dictModuleTask[outLL].TimeToReady < 2 && _dictModuleTask[outLL].Scheduler.IsAtm)                                                                 || _efemRobotSingleArmOption != 0                                                                 || _lstWaferTasks.Where(wt => ModuleHelper.IsLoadPort(wt.destMod)).Count() == 1)))                {                    if (ExchangeWaferWithLL(outLL))                        return;                }                // need pass by aligner                if(_lstProcessJobs.Exists(pj => pj.State == EnumProcessJobState.Processing && IsSequenceNeedAlign(pj.Sequence)))                {                    if (atmWaferCount == 0 || (atmWaferCount == 1 && inLLWaferStatus.emptySlot.Count == 2 && _efemRobotSingleArmOption == 0 && (outLLWaferStatus.outSlot.Count < 2)))                    {                        if (ForwardATMWafers(inLL))                            return;                    }                    }                // don need pass by aligner                else                {                    var outModule = _dictModuleTask[outLL] as LoadlockTask;                    if ((atmWaferCount < validHands - outModule.ReayOutWafersInTime(20) || _dictModuleTask[inLL].TimeToReady < 5) && _lstWaferTasks.Count(wt => wt.currentMod == inLL || wt.currentMod == ModuleName.EfemRobot) < validHands)                    {                        if (ForwardATMWafers(inLL))                            return;                    }                }                if (inLLWaferStatus.emptySlot.Count >= validHands && _dictModuleTask[inLL].TimeToReady < 2)                {                    ExchangeWaferWithLL(inLL);                }            }            else            {                RoutingSameLLInOutATMSystem();            }        }        private void RoutingFixedSlotATMSystem()        {            var atmWaferCount = _lstWaferTasks.Where(wafer => ModuleHelper.IsEFEMRobot(wafer.currentMod) || ModuleHelper.IsAligner(wafer.currentMod)).Count();            var lls = _dictModuleTask.Where(mod => ModuleHelper.IsLoadLock(mod.Key) && mod.Value.Scheduler.IsOnline);            if ( atmWaferCount == 0 || (_efemRobotSingleArmOption == 0 && atmWaferCount == 1 ))            {                foreach(var ll in lls)                {                    if (ForwardATMWafers(ll.Key))                        return;                }            }            // try to match a ll swap action            var readyReturnLL = lls.Where(ll => (GetLLFixedReadyInOutSlots(ll.Key).eOutSlot.Count + GetLLFixedReadyInOutSlots(ll.Key).eInSlot.Count > 0) && ll.Value.TimeToReady <= 10)                                            .OrderByDescending(ll => GetLLFixedReadyInOutSlots(ll.Key).eInSlot.Count + GetLLFixedReadyInOutSlots(ll.Key).eOutSlot.Count)                                            .OrderBy(ll => ll.Value.TimeToReady);            foreach (var ll in readyReturnLL)            {                if (ExchangeWaferWithFixedSlotLL(ll.Key))                    return;            }        }        private void RoutingSameLLInOutATMSystem()        {            var atmWaferCount = _lstWaferTasks.Where(wafer => ModuleHelper.IsEFEMRobot(wafer.currentMod) || ModuleHelper.IsAligner(wafer.currentMod)).Count();            var vacWaferCount = _lstWaferTasks.Where(task => ModuleHelper.IsPm(task.currentMod) || ModuleHelper.IsTMRobot(task.currentMod) || ModuleHelper.IsLoadLock(task.currentMod)).Count();            var preferWaferVacCount = _dictModuleTask.Where(mod => ModuleHelper.IsPm(mod.Key) && mod.Value.Scheduler.IsOnline).Count() +                                      (LLInOutPath == SequenceLLInOutPath.AInAOut ? _LLASlotNumber / 2 : (LLInOutPath == SequenceLLInOutPath.BInBOut ? _LLBSlotNumber / 2 : _LLASlotNumber));            var inOutIndicator = vacWaferCount - preferWaferVacCount;            if (inOutIndicator < 0)            {                // ready to push in                 var readyLLs = _dictModuleTask.Where(mod => ModuleHelper.IsLoadLock(mod.Key) &&                        ((mod.Key == ModuleName.LLA && LLInOutPath != SequenceLLInOutPath.BInBOut) || (mod.Key == ModuleName.LLB && LLInOutPath != SequenceLLInOutPath.AInAOut)) &&                        mod.Value.TimeToReady <= 10 &&                        !IsLLReservedByTM(mod.Key) &&                        GetLLReadyInOutSlots(mod.Key).emptySlot.Count >= 1).                        OrderBy(mod => mod.Value.TimeToReady).ToList();                if (atmWaferCount >= 1)                {                    foreach(var ll in readyLLs)                    {                        if (ExchangeWaferWithLL(ll.Key))                            return;                    }                }                // forward wafer to system                if (atmWaferCount < 2)                {                    var targetLL = readyLLs.Count > 0 ? readyLLs.First().Key : (LLInOutPath == SequenceLLInOutPath.BInBOut ? ModuleName.LLB : ModuleName.LLA);                    ForwardATMWafers(targetLL);                }                if (_efemSchdActions.Count == 0)                {                    var readyReturnLL = _dictModuleTask.Where(mod => ModuleHelper.IsLoadLock(mod.Key) &&                            ((mod.Key == ModuleName.LLA && LLInOutPath != SequenceLLInOutPath.BInBOut) || (mod.Key == ModuleName.LLB && LLInOutPath != SequenceLLInOutPath.AInAOut)) &&                            mod.Value.TimeToReady <= 5 &&                            !IsLLReservedByTM(mod.Key) &&                            GetLLReadyInOutSlots(mod.Key).outSlot.Count >= 1).                            OrderByDescending(mod => GetLLReadyInOutSlots(mod.Key).outSlot.Count).ToList();                    foreach(var ll in readyReturnLL)                    {                        if (ExchangeWaferWithLL(readyReturnLL.First().Key))                            return;                    }                }            }            else            {                // ready double return LL                var readyDoubleReturnLL = _dictModuleTask.Where(mod => ModuleHelper.IsLoadLock(mod.Key) &&                        mod.Value.TimeToReady < 10 &&                        !IsLLReservedByTM(mod.Key) &&                        GetLLReadyInOutSlots(mod.Key).outSlot.Count > 1).                        OrderBy(mod => mod.Value.TimeToReady).ToList();                foreach(var ll in readyDoubleReturnLL)                {                    if (ExchangeWaferWithLL(ll.Key))                        return;                }                // ready single return LL                var readySingleReturnLL = _dictModuleTask.Where(mod => ModuleHelper.IsLoadLock(mod.Key) &&                        mod.Value.TimeToReady < 2 &&                        !IsLLReservedByTM(mod.Key) &&                        GetLLReadyInOutSlots(mod.Key).outSlot.Count == 1).                        OrderBy(mod => mod.Value.TimeToReady).ToList();                foreach (var ll in readySingleReturnLL)                {                    if (ExchangeWaferWithLL(ll.Key))                        return;                }                if (atmWaferCount == 0)                {                    // ready to push in                     var readyLLs = _dictModuleTask.Where(mod => ModuleHelper.IsLoadLock(mod.Key) &&                            ((mod.Key != ModuleName.LLA && LLInOutPath == SequenceLLInOutPath.BInBOut) || (mod.Key != ModuleName.LLB && LLInOutPath == SequenceLLInOutPath.AInAOut)) &&                            mod.Value.TimeToReady <= 10 &&                            !IsLLReservedByTM(mod.Key) &&                            GetLLReadyInOutSlots(mod.Key).emptySlot.Count > 1).                            OrderBy(mod => mod.Value.TimeToReady).ToList();                    foreach(var ll in readyLLs)                    {                        if (ForwardATMWafers(ll.Key))                            return;                    }                }            }        }        private bool isReturnActionsDone(List<MoveItem> items)        {            foreach(var item in items)            {                if (WaferManager.Instance.CheckHasWafer(item.SourceModule, item.SourceSlot) || WaferManager.Instance.CheckNoWafer(item.DestinationModule, item.DestinationSlot))                    return false;            }            return true;        }        private bool IsMovingActionsDone(List<MoveItem> actions)        {            bool CheckWaferExistence(ModuleName mod, int slot)            {                return ModuleHelper.IsLoadPort(mod) ? WaferManager.Instance.CheckHasWafer(mod, slot) : _lstWaferTasks.Exists(wt => wt.currentMod == mod && wt.currentSlot == slot);            }            if(actions.Count == 1)            {                if ( CheckWaferExistence(actions.First().SourceModule, actions.First().SourceSlot) ||                    !CheckWaferExistence(actions.First().DestinationModule, actions.First().DestinationSlot) )                    return false;            }            else            {                // initialize all the wafer existance before move                var slotWafers = new Dictionary<KeyValuePair<ModuleName, int>, bool>();                foreach (var ac in actions)                {                    var scrSlot = new KeyValuePair<ModuleName, int>(ac.SourceModule, ac.SourceSlot);                    var destSlot = new KeyValuePair<ModuleName, int>(ac.DestinationModule, ac.DestinationSlot);                    if (!slotWafers.ContainsKey(scrSlot))                    {                        slotWafers[scrSlot] = true;                    }                    if (!slotWafers.ContainsKey(destSlot))                    {                        slotWafers[destSlot] = false;                    }                }                // simulate moved result                foreach (var ac in actions)                {                    var scrSlot = new KeyValuePair<ModuleName, int>(ac.SourceModule, ac.SourceSlot);                    var destSlot = new KeyValuePair<ModuleName, int>(ac.DestinationModule, ac.DestinationSlot);                    if (!slotWafers[scrSlot])                    {                        LOG.Write(eEvent.WARN_ROUTER, ModuleName.System, $"{slotWafers[scrSlot]} do not has a wafer");                    }                    else                    {                        slotWafers[scrSlot] = false;                    }                    if (slotWafers[destSlot])                    {                        LOG.Write(eEvent.WARN_ROUTER, ModuleName.System, $"{slotWafers[destSlot]}  has a wafer");                    }                    else                    {                        slotWafers[destSlot] = true;                    }                }                foreach (var slot in slotWafers)                {                    if (slot.Value != CheckWaferExistence(slot.Key.Key, slot.Key.Value))                        return false;                }            }            return true;        }        private bool IsLLReservedByTM(ModuleName ll)        {            foreach(var item in _curTmAction)            {                if (item.DestinationModule == ll || item.SourceModule == ll)                    return true;            }            foreach(var action in _tmSchdActions)            {                foreach(var item in action)                {                    if (item.DestinationModule == ll || item.SourceModule == ll)                        return true;                }            }            return false;        }        private bool IsLLReservedByEFEM(ModuleName ll)        {            foreach (var item in _curEfemAction)            {                if (item.DestinationModule == ll || item.SourceModule == ll)                    return true;            }            foreach (var action in _efemSchdActions)            {                foreach (var item in action)                {                    if (item.DestinationModule == ll || item.SourceModule == ll)                        return true;                }            }            return false;        }        private void RunSchdEFEMActions()        {            var efemRobot = Singleton<TransferModule>.Instance.GetScheduler(ModuleName.EfemRobot) as SchedulerEfemRobot;            if (efemRobot == null || !efemRobot.IsAvailable)                return;               if (_dictModuleTask[ModuleName.EfemRobot].IsIdle)            {                if(_efemSchdActions.Count > 0 )                {                    if(_curEfemAction.Count == 0 || IsMovingActionsDone(_curEfemAction))                    {                        var nextActions = _efemSchdActions.First();                        if (nextActions.Exists(action => !_lstWaferTasks.Exists(wafer => (wafer.movingStatus == RState.End || wafer.movingStatus == RState.Init) && wafer.currentMod == action.SourceModule && wafer.currentSlot == action.SourceSlot)))                            return;                        var nextModule = nextActions.First().Module;                        if (ModuleHelper.IsLoadLock(nextModule) && !_dictModuleTask[nextModule].IsIdle)                            return;                        _curEfemAction = _efemSchdActions.Dequeue();                        foreach (var action in _curEfemAction)                        {                            var waferTask = _lstWaferTasks.Find(wafer => (wafer.movingStatus == RState.End || wafer.movingStatus == RState.Init) && wafer.currentMod == action.SourceModule && wafer.currentSlot == action.SourceSlot);                            waferTask.MoveTo(action.DestinationModule, action.DestinationSlot);                            //--2024-03-21 增加了PortJobWaferStart 上报事件 start--                            if (ModuleHelper.IsLoadPort(action.SourceModule))                            {                                ControlJobInfo currentControlJob = GetLoadPortCurrentControlJob(action.SourceModule);                                if(currentControlJob!=null)                                {                                    _faCallback.JobWaferStart(currentControlJob, action.SourceSlot);                                }                            }                            if(ModuleHelper.IsLoadPort(action.DestinationModule))                            {                                ControlJobInfo currentControlJob = GetLoadPortCurrentControlJob(action.DestinationModule);                                if (currentControlJob != null)                                {                                    _faCallback.JobWaferEnd(currentControlJob, action.SourceSlot);                                }                            }                            //--2024-03-21 增加了PortJobWaferStart 上报事件 end--                        }                        (_dictModuleTask[ModuleName.EfemRobot].Scheduler as SchedulerEfemRobot).PostMoveItems(_curEfemAction.ToArray());                    }                }                else if(_curEfemAction.Count >= 0 && IsMovingActionsDone(_curEfemAction)) // all scheduled actions done                {                    _curEfemAction.Clear();                }            }        }        private void RunSchdTMActions()        {            if (_dictModuleTask[ModuleName.TMRobot].IsIdle)            {                if (_tmSchdActions.Count > 0)                {                    if (_curTmAction.Count == 0 || IsMovingActionsDone(_curTmAction))                    {                        var nextActions = _tmSchdActions.First();                        if (nextActions.Exists(action => !_lstWaferTasks.Exists(wafer => (wafer.movingStatus == RState.End || wafer.movingStatus == RState.Init) && wafer.currentMod == action.SourceModule && wafer.currentSlot == action.SourceSlot)))                            return;                        if (ModuleHelper.IsPm(nextActions.First().Module) && !_dictModuleTask[nextActions.First().Module].IsIdle)  /// wait PMTask status update to idle                            return;                        _curTmAction = _tmSchdActions.Dequeue();                        foreach(var action in _curTmAction)                        {                            var waferTask = _lstWaferTasks.Find(wafer => (wafer.movingStatus == RState.End || wafer.movingStatus == RState.Init) && wafer.currentMod == action.SourceModule && wafer.currentSlot == action.SourceSlot);                            waferTask.MoveTo(action.DestinationModule, action.DestinationSlot);                        }                        (_dictModuleTask[ModuleName.TMRobot].Scheduler as SchedulerTMRobot).SendMoveItems(_curTmAction.ToArray());                    }                }                else if (_curTmAction.Count >= 0 && IsMovingActionsDone(_curTmAction)) // all scheduled actions done                {                    _curTmAction.Clear();                }            }        }        private int TimeForNextModuleReady(WaferTask task)        {            if (ModuleHelper.IsPm(task.destMod) && (ModuleHelper.IsLoadLock(task.currentMod) || ModuleHelper.IsTMRobot(task.currentMod)))                return _dictModuleTask[task.destMod].TimeToReady;            var llbWaferStatus = GetLLReadyInOutSlots(ModuleName.LLB);            var llaWaferStatus = GetLLReadyInOutSlots(ModuleName.LLA);            if (ModuleHelper.IsLoadPort(task.destMod) && (ModuleHelper.IsPm(task.currentMod) || ModuleHelper.IsTMRobot(task.currentMod)))            {                if (task.llInOutPath == SequenceLLInOutPath.AInBOut || task.llInOutPath == SequenceLLInOutPath.BInBOut)                {                    if(llbWaferStatus.emptySlot.Count > 0)                    {                        return _dictModuleTask[ModuleName.LLB].TimeToReady;                    }                }                else if(task.llInOutPath == SequenceLLInOutPath.BInAOut || task.llInOutPath == SequenceLLInOutPath.AInAOut)                {                    if(llaWaferStatus.emptySlot.Count > 0)                    {                        return _dictModuleTask[ModuleName.LLA].TimeToReady;                    }                }                else if(task.llInOutPath == SequenceLLInOutPath.DInDOut)                {                    if(llaWaferStatus.emptySlot.Count > 0 && llbWaferStatus.emptySlot.Count > 0)                    {                        if (_dictModuleTask[ModuleName.LLA].TimeToReady == _dictModuleTask[ModuleName.LLB].TimeToReady)                        {                            return _dictModuleTask[ModuleName.LLA].TimeToReady;                        }                        else                        {                            return Math.Min(_dictModuleTask[ModuleName.LLA].TimeToReady, _dictModuleTask[ModuleName.LLB].TimeToReady);                        }                    }                    else if(llaWaferStatus.emptySlot.Count > 0)                    {                        return _dictModuleTask[ModuleName.LLA].TimeToReady;                    }                    else if(llbWaferStatus.emptySlot.Count > 0)                    {                        return _dictModuleTask[ModuleName.LLB].TimeToReady;                    }                }            }            else if(ModuleHelper.IsPm(task.destMod) && (ModuleHelper.IsLoadLock(task.currentMod) || ModuleHelper.IsTMRobot(task.currentMod)))            {                if(_lstWaferTasks.Find(wafer => wafer.currentMod == task.destMod || wafer.routedMod == task.destMod) == null)                {                    return _dictModuleTask[task.destMod].TimeToReady;                }            }            return int.MaxValue;        }        List<Hand> GetTMValidFreeHands(List<WaferTask> robotWafers, List<MoveItem> swapActions)        {            var hands = new List<Hand>();            for(int i = 0; i < 2; i++)            {                if(_tmRobotSingleArmOption == 0 || _tmRobotSingleArmOption == i + 1)                {                    if ((!robotWafers.Exists(wafer => wafer.currentSlot == i) ||                            ( robotWafers.Exists(wafer => wafer.currentSlot == i) &&                              swapActions.Exists(item => item.SourceModule == ModuleName.TMRobot && item.SourceSlot == i))) &&                        !swapActions.Exists(item => item.DestinationModule == ModuleName.TMRobot && item.DestinationSlot == i))                        hands.Add((Hand)i);                }            }            return hands;        }        (ModuleName llPath, List<MoveItem> swapActions) FindBestLLSwapPlan(ModuleName ll, List<WaferTask> robotWafers)        {            ModuleName path = ll == ModuleName.System ? ModuleName.System : ll;            List<ModuleName> lls = ll == ModuleName.System ? new List<ModuleName> { ModuleName.LLA, ModuleName.LLB } : new List<ModuleName> { ll };            List<MoveItem> actions = new List<MoveItem>();            Dictionary<ModuleName, List<MoveItem>> llSwapActions = new Dictionary<ModuleName, List<MoveItem>>();            foreach (var loadlock in lls)            {                llSwapActions[loadlock] = new List<MoveItem>();                if (IsLLReservedByEFEM(loadlock))                    continue;                var llWaferStatus = GetLLReadyInOutSlots(loadlock);                foreach(var wafer in robotWafers)                {                    if(_dictModuleTask[loadlock].TimeToReady == 0 && !IsLLReservedByEFEM(loadlock) && CanWaferGotoLL(wafer,loadlock) && llWaferStatus.emptySlot.Count > llSwapActions[loadlock].Count)                    {                        llSwapActions[loadlock].Add(new MoveItem(ModuleName.TMRobot, wafer.currentSlot, loadlock, llWaferStatus.emptySlot[llSwapActions[loadlock].Count], (Hand)wafer.currentSlot));                    }                }                int prePickTime = 20;                int prePickCount = 0;                var hands = GetTMValidFreeHands(robotWafers, llSwapActions[loadlock]);                foreach (var slot in llWaferStatus.inSlot)                {                    var wafer = _lstWaferTasks.Find(task => task.currentMod == loadlock && task.currentSlot == slot);                    if (wafer != null && _dictModuleTask[wafer.destMod].TimeToReady <= prePickTime && _dictModuleTask[wafer.destMod].Scheduler.IsOnline && hands.Count > prePickCount)                    {                        if(_lstWaferTasks.Exists(task => task.currentMod == wafer.destMod))                        {                            if( hands.Count == 2 && prePickCount == 0 && (_dictModuleTask.Count(mod => ModuleHelper.IsPm(mod.Key) && mod.Value.TimeToReady < prePickTime && WaferManager.Instance.CheckNoWafer(mod.Key, 0)) == 0 || llWaferStatus.inSlot.Count == 1))                            {                                llSwapActions[loadlock].Add(new MoveItem(loadlock, slot, ModuleName.TMRobot, (int)hands[prePickCount], hands[prePickCount]));                                prePickCount++;                                break;                            }                        }                        else                        {                            llSwapActions[loadlock].Add(new MoveItem(loadlock, slot, ModuleName.TMRobot, (int)hands[prePickCount], hands[prePickCount]));                            prePickCount++;                        }                    }                }            }            var validateActions = llSwapActions.Where(item => item.Value.Count > 0).ToDictionary(k => k.Key, v => v.Value);            if(validateActions.Count == 1)            {                (path, actions) = (validateActions.First().Key, validateActions.First().Value);            }            else if(validateActions.Count == 2)            {                var sortedActions = validateActions.OrderByDescending(item => item.Value.Count + (_dictModuleTask[item.Key].Scheduler.IsVac ? 2 : 0)).ToDictionary(k => k.Key, v => v.Value);                (path, actions) = (sortedActions.First().Key, sortedActions.First().Value);            }            return (path, actions);        }        (List<WaferTask> pmWafers, ModuleName destLL, List<MoveItem> swapAction) FindBestReturnWafersPlan(Hand[] freeHands)        {            Dictionary<ModuleName, List<WaferTask>> returnWafers = new Dictionary<ModuleName, List<WaferTask>>();            Dictionary<ModuleName, List<MoveItem>> llSwapActions = new Dictionary<ModuleName, List<MoveItem>>();            Dictionary<ModuleName, int> llValues = new Dictionary<ModuleName, int>();            foreach(var ll in new List<ModuleName> { ModuleName.LLA, ModuleName.LLB})            {                var llWaferStatus = GetLLReadyInOutSlots(ll);                returnWafers[ll] = new List<WaferTask>();                llSwapActions[ll] = new List<MoveItem>();                llValues[ll] = 0;                if (IsLLReservedByEFEM(ll))                    continue;                var readyReturnWafers = _lstWaferTasks.Where( wafer => ModuleHelper.IsPm(wafer.currentMod) &&                                                                ModuleHelper.IsLoadPort(wafer.destMod) &&                                                                wafer.movingStatus == RState.End &&                                                                _dictModuleTask[wafer.currentMod].TimeToReady <= 2 &&                                                                 CanWaferGotoLL(wafer, ll)).Take(Math.Min(freeHands.Length, llWaferStatus.emptySlot.Count)).ToList();                int prePickTime = 10 * llSwapActions[ll].Count;                int handIndex = 0;                if(_dictModuleTask[ll].TimeToReady <= prePickTime)                {                    foreach (var wafer in readyReturnWafers)                    {                        if(handIndex < freeHands.Length)                        {                            returnWafers[ll].Add(wafer);                            llSwapActions[ll].Add(new MoveItem(ModuleName.TMRobot, (int)freeHands[handIndex], ll, llWaferStatus.emptySlot[handIndex], freeHands[handIndex]));                            handIndex++;                        }                    }                    int prePickCount = 0;                    handIndex = 0;                    foreach (var slot in llWaferStatus.inSlot)                    {                        var wafer = _lstWaferTasks.Find(task => task.currentMod == ll && task.currentSlot == slot);                        if (wafer != null && _dictModuleTask[wafer.destMod].TimeToReady <= prePickTime && _dictModuleTask[wafer.destMod].Scheduler.IsOnline && freeHands.Length > prePickCount)                        {                            if (_lstWaferTasks.Exists(task => task.currentMod == wafer.destMod))                            {                                if (freeHands.Length == 2 && prePickCount == 0 && (_dictModuleTask.Count(mod => ModuleHelper.IsPm(mod.Key) && mod.Value.TimeToReady <= prePickTime && WaferManager.Instance.CheckNoWafer(mod.Key, 0)) == 0 || llWaferStatus.inSlot.Count == 1))                                {                                    llSwapActions[ll].Add(new MoveItem(ll, slot, ModuleName.TMRobot, (int)freeHands[prePickCount], freeHands[prePickCount]));                                    prePickCount++;                                    break;                                }                            }                            else                            {                                llSwapActions[ll].Add(new MoveItem(ll, slot, ModuleName.TMRobot, (int)freeHands[prePickCount], freeHands[prePickCount]));                                prePickCount++;                            }                        }                    }                    llValues[ll] = returnWafers[ll].Count * 2 + llSwapActions[ll].Count + (_dictModuleTask[ll].Scheduler.IsVac && returnWafers[ll].Count > 0 ? 2 : 0);                }            }            var preferLL = llValues.OrderByDescending(v => v.Value).First().Key;            return (returnWafers[preferLL], preferLL, llSwapActions[preferLL]);        }        ModuleName FindTheBestMovePathWithFixSlot(IEnumerable<KeyValuePair<ModuleName, ModuleTask>> lls, List<WaferTask> pmWafers)        {            Dictionary<ModuleName, int> moveValues = new Dictionary<ModuleName, int>();            foreach(var ll in lls)            {                var llWaferStatus = GetLLFixedReadyInOutSlots(ll.Key);                moveValues[ll.Key] = Math.Min(pmWafers.Where(wt => CanWaferGotoLL(wt, ll.Key)).Count(), GetLLFixedReadyInOutSlots(ll.Key).tInSlot.Count) + llWaferStatus.tOutSlot.Count;            }            var preferLL = moveValues.OrderByDescending(v => v.Value).First().Key;            return moveValues[preferLL] > 0 ? preferLL : ModuleName.System;        }        void RoutingTMSwapActions(List<MoveItem> actions)        {            foreach (var action in actions)            {                if (ModuleHelper.IsTMRobot(action.SourceModule))                {                    var waferTask = _lstWaferTasks.Find(wafer => wafer.currentMod == ModuleName.TMRobot && wafer.currentSlot == action.SourceSlot);                    waferTask.RouteTo(action.DestinationModule, action.DestinationSlot);                }                else                {                    var waferTask = _lstWaferTasks.Find(wafer => wafer.currentMod == action.SourceModule && wafer.currentSlot == action.SourceSlot);                    waferTask.RouteTo(action.DestinationModule, action.DestinationSlot);                }            }        }        private bool ManaulReturnPMWafer()        {            var mReturnWafer = _qeReturnWafers.Peek();            if (ModuleHelper.IsPm((ModuleName)mReturnWafer.Station))            {                var hands = GetTMValidFreeHands(_lstWaferTasks.Where(wt => ModuleHelper.IsTMRobot(wt.currentMod)).ToList(), new List<MoveItem>());                var waferTask = _lstWaferTasks.Find(wt => wt.currentMod == (ModuleName)mReturnWafer.Station && wt.waferId == mReturnWafer.InnerId);                if (waferTask != null && hands.Count > 0)                {                    waferTask.Return();                    var outLL = _dictModuleTask.Where(mod => ModuleHelper.IsLoadLock(mod.Key) && CanWaferGotoLL(waferTask, mod.Key) && GetLLReadyInOutSlots(mod.Key).emptySlot.Count > 0 && !IsLLReservedByEFEM(mod.Key));                    if (outLL.Count() > 0)                    {                        var slot = GetLLReadyInOutSlots(outLL.First().Key).emptySlot.First();                        waferTask.RouteTo(outLL.First().Key, slot);                        _tmSchdActions.Enqueue(new List<MoveItem> { new MoveItem(waferTask.currentMod, 0, ModuleName.TMRobot, (int)hands.First(), hands.First()) });                        _tmSchdActions.Enqueue(new List<MoveItem> { new MoveItem(ModuleName.TMRobot, (int)hands.First(), outLL.First().Key, slot, hands.First()) });                        _qeReturnWafers.Dequeue();                        return true;                    }                }            }            return false;        }        private void RoutingVacWafers()        {            if(_tmSchdActions.Count > 0 || _curTmAction.Count > 0)            {                RunSchdTMActions();                return;            }            if(_tmRobotStatus == RState.End)            {                // handle manual return wafer if exist                if(_qeReturnWafers.Count > 0)                {                    if (ManaulReturnPMWafer())                        return;                }                if(_LLSlotInOutOption == LLSlotInOutOpt.AllInAllOut)                {                    if (_LLASlotNumber == 2)                    {                        Routing2SlotVacSystem();                    }                    else if (_LLASlotNumber == 4)                    {                        Routing4SlotVacSystem();                    }                }                else                {                    RoutingFixedSlotVacSystem();                }            }        }        private void Routing2SlotVacSystem()        {            var robotWafers = _lstWaferTasks.Where(wafer => (wafer.movingStatus == RState.End || wafer.movingStatus == RState.Init) && ModuleHelper.IsTMRobot(wafer.currentMod)).OrderBy(wafer => TimeForNextModuleReady(wafer)).ToList();            if (LLInOutPath == SequenceLLInOutPath.AInBOut || LLInOutPath == SequenceLLInOutPath.BInAOut)            {                var inLL = LLInOutPath == SequenceLLInOutPath.AInBOut ? ModuleName.LLA : ModuleName.LLB;                var outLL = LLInOutPath == SequenceLLInOutPath.AInBOut ? ModuleName.LLB : ModuleName.LLA;                var inLLWaferStatus = GetLLReadyInOutSlots(inLL);                var outLLWaferStatus = GetLLReadyInOutSlots(outLL);                if(robotWafers.Count == 2)                {                    int returnCount = 0;                    foreach (var wafer in robotWafers)                    {                        if (ModuleHelper.IsPm(wafer.destMod))                        {                            if (_dictModuleTask[wafer.destMod].TimeToReady <= 5 &&                                !_lstWaferTasks.Exists(waferT => waferT.currentMod == wafer.destMod) &&                                !_lstWaferTasks.Exists(waferT => waferT.routedMod == wafer.destMod))                            {                                wafer.RouteTo(wafer.destMod, 0);                                _tmSchdActions.Enqueue(new List<MoveItem> { new MoveItem(ModuleName.TMRobot, wafer.currentSlot, wafer.destMod, 0, (Hand)wafer.currentSlot) });                            }                        }                        else                        {                            if (_dictModuleTask[outLL].TimeToReady <= 5 && !IsLLReservedByEFEM(outLL) && outLLWaferStatus.emptySlot.Count > returnCount)                            {                                wafer.RouteTo(outLL, outLLWaferStatus.emptySlot[returnCount]);                                _tmSchdActions.Enqueue(new List<MoveItem> { new MoveItem(ModuleName.TMRobot, wafer.currentSlot, outLL, outLLWaferStatus.emptySlot[returnCount], (Hand)wafer.currentSlot) });                                returnCount++;                            }                        }                    }                }                else if(robotWafers.Count == 1)                {                    int freeHand = 1 - robotWafers.First().currentSlot;                    if (ModuleHelper.IsPm(robotWafers.First().destMod))                    {                        if(_dictModuleTask[robotWafers.First().destMod].TimeToReady <= 5)                        {                            if(_lstWaferTasks.Exists(waferT => waferT.currentMod == robotWafers.First().destMod))                            {                                var pmActions = new List<MoveItem>();                                var pmWafer = _lstWaferTasks.Find(wafer => wafer.currentMod == robotWafers.First().destMod);                                pmWafer.RouteTo(ModuleName.TMRobot, freeHand);                                pmActions.Add(new MoveItem(pmWafer.currentMod, 0, ModuleName.TMRobot, freeHand, (Hand)freeHand));                                pmActions.Add(new MoveItem(ModuleName.TMRobot, robotWafers.First().currentSlot, pmWafer.currentMod, 0, (Hand)robotWafers.First().currentSlot));                                _tmSchdActions.Enqueue(pmActions);                            }                            else                            {                                robotWafers.First().RouteTo(robotWafers.First().destMod, 0);                                _tmSchdActions.Enqueue(new List<MoveItem> { new MoveItem(ModuleName.TMRobot, robotWafers.First().currentSlot, robotWafers.First().destMod, 0, (Hand)robotWafers.First().currentSlot) });                            }                        }                    }                    else                    {                        if (_dictModuleTask[outLL].TimeToReady <= 5 && !IsLLReservedByEFEM(outLL) && outLLWaferStatus.emptySlot.Count > 0)                        {                            robotWafers.First().RouteTo(outLL, outLLWaferStatus.emptySlot[0]);                            _tmSchdActions.Enqueue(new List<MoveItem> { new MoveItem(ModuleName.TMRobot, robotWafers.First().currentSlot, outLL, outLLWaferStatus.emptySlot[0], (Hand)robotWafers.First().currentSlot) });                        }                    }                    if (_tmSchdActions.Count == 0 && _tmRobotSingleArmOption == 0)                    {                        // try push in one wafer                        if (!IsLLReservedByEFEM(inLL) && _dictModuleTask[inLL].TimeToReady < 5 && inLLWaferStatus.inSlot.Count > 0)                        {                            foreach (var slot in inLLWaferStatus.inSlot)                            {                                var llWafer = _lstWaferTasks.Find(wafer => wafer.currentMod == inLL && wafer.currentSlot == slot);                                if (llWafer != null && !_lstWaferTasks.Exists(wt => wt.currentMod == llWafer.destMod) && _dictModuleTask[llWafer.destMod].TimeToReady < 15)                                {                                    llWafer.RouteTo(llWafer.destMod, 0);                                    _tmSchdActions.Enqueue(new List<MoveItem> { new MoveItem(inLL, slot, ModuleName.TMRobot, freeHand, (Hand)freeHand) });                                    _tmSchdActions.Enqueue(new List<MoveItem> { new MoveItem(ModuleName.TMRobot, freeHand, llWafer.destMod, 0, (Hand)freeHand) });                                    return;                                }                            }                        }                        // try to return one wafer                        if (!IsLLReservedByEFEM(outLL) && outLLWaferStatus.emptySlot.Count > 0)                        {                            var reayReturnWafer = _lstWaferTasks.Find(wt => ModuleHelper.IsPm(wt.currentMod) && ModuleHelper.IsLoadPort(wt.destMod) && _dictModuleTask[wt.currentMod].TimeToReady <= 2);                            if (reayReturnWafer != null)                            {                                reayReturnWafer.RouteTo(outLL, outLLWaferStatus.emptySlot[0]);                                _tmSchdActions.Enqueue(new List<MoveItem> { new MoveItem(reayReturnWafer.currentMod, 0, ModuleName.TMRobot, freeHand, (Hand)freeHand) });                                _tmSchdActions.Enqueue(new List<MoveItem> { new MoveItem(ModuleName.TMRobot, freeHand, outLL, outLLWaferStatus.emptySlot[0], (Hand)freeHand) });                                return;                            }                        }                    }                }                else // no wafer on robot arm                {                    var readyInPms = _dictModuleTask.Where(mod => ModuleHelper.IsPm(mod.Key) && !_lstWaferTasks.Exists(wt => wt.currentMod == mod.Key) && mod.Value.Scheduler.IsOnline && mod.Value.TimeToReady <= 15);                    var readyOutWafers = _lstWaferTasks.Where(wt => ModuleHelper.IsPm(wt.currentMod) && ModuleHelper.IsLoadPort(wt.destMod) && _dictModuleTask[wt.currentMod].TimeToReady <= 2).ToList() ;                    if(_tmRobotSingleArmOption != 0)                    {                        var hands = GetTMValidFreeHands(robotWafers, new List<MoveItem>());                        if (hands.Count == 0)                            return;                        if(!IsLLReservedByEFEM(inLL) && _dictModuleTask[inLL].TimeToReady <= 5 && inLLWaferStatus.inSlot.Count > 0 && readyInPms.Count() > 0)                        {                            foreach(var pm in readyInPms)                            {                                var llWafer = _lstWaferTasks.Find(wt => wt.currentMod == inLL && inLLWaferStatus.inSlot.Contains(wt.currentSlot) && wt.destMod == pm.Key);                                if(llWafer != null)                                {                                    llWafer.RouteTo(llWafer.destMod, 0);                                    _tmSchdActions.Enqueue(new List<MoveItem> { new MoveItem(inLL, llWafer.currentSlot, ModuleName.TMRobot, (int)hands.First(), hands.First()) });                                    _tmSchdActions.Enqueue(new List<MoveItem> { new MoveItem(ModuleName.TMRobot, (int)hands.First(), llWafer.destMod, 0, hands.First()) });                                    return;                                }                            }                        }                                                if(readyOutWafers.Count > 0 && !IsLLReservedByEFEM(outLL) && _dictModuleTask[outLL].TimeToReady < 50 && outLLWaferStatus.emptySlot.Count > 0)                        {                            var returnWafer = readyOutWafers.First();                            returnWafer.RouteTo(outLL, outLLWaferStatus.emptySlot.First());                            _tmSchdActions.Enqueue(new List<MoveItem> { new MoveItem(returnWafer.currentMod, 0, ModuleName.TMRobot, (int)hands.First(), hands.First()) });                            _tmSchdActions.Enqueue(new List<MoveItem> { new MoveItem(ModuleName.TMRobot, (int)hands.First(), outLL, outLLWaferStatus.emptySlot.First(), hands.First()) });                            return;                        }                        return;                    }                    if(!IsLLReservedByEFEM(inLL) && _dictModuleTask[inLL].TimeToReady <= 5 && inLLWaferStatus.inSlot.Count > 0)                    {                        if(inLLWaferStatus.inSlot.Count == 2)                        {                            if(readyInPms.Count() > 0) // double move from LL to PM                            {                                int pickCount = 0;                                var swapActions = new List<MoveItem>();                                var singleActions = new List<MoveItem>();                                foreach(var pm in readyInPms)                                {                                    var llWafer = _lstWaferTasks.Find(wt => wt.currentMod == inLL && inLLWaferStatus.inSlot.Contains(wt.currentSlot) && wt.destMod == pm.Key);                                    if(llWafer != null)                                    {                                        llWafer.RouteTo(pm.Key, 0);                                        swapActions.Add(new MoveItem(inLL, llWafer.currentSlot, ModuleName.TMRobot, pickCount, (Hand)pickCount));                                        singleActions.Add(new MoveItem(ModuleName.TMRobot, pickCount, pm.Key, 0, (Hand)pickCount));                                        pickCount++;                                    }                                }                                if(pickCount == 1)                                {                                    int remainSlot = swapActions.First().SourceSlot == inLLWaferStatus.inSlot[0] ? inLLWaferStatus.inSlot[1] : inLLWaferStatus.inSlot[0];                                    var remainWafer = _lstWaferTasks.Find(wt => wt.currentMod == inLL && wt.currentSlot == remainSlot);                                    if (remainWafer != null)                                    {                                        remainWafer.RouteTo(ModuleName.TMRobot, 1);                                        swapActions.Add(new MoveItem(inLL, remainSlot, ModuleName.TMRobot, 1, Hand.Blade2));                                    }                                }                                if(swapActions.Count > 0)                                {                                    _tmSchdActions.Enqueue(swapActions);                                    foreach(var ac in singleActions)                                    {                                        _tmSchdActions.Enqueue(new List<MoveItem> { ac });                                    }                                }                            }                            else                            {                                foreach(var slot in inLLWaferStatus.inSlot)                                {                                    var llWafer = _lstWaferTasks.Find(wt => wt.currentMod == inLL && wt.currentSlot == slot);                                    if (llWafer != null)                                    {                                        if(!_lstWaferTasks.Exists(wt => wt.currentMod == llWafer.destMod) && _dictModuleTask[llWafer.destMod].Scheduler.IsOnline)                                        {                                            var swapActions = new List<MoveItem>();                                            swapActions.Add(new MoveItem(inLL, slot, ModuleName.TMRobot, 0, Hand.Blade1));                                            int remainSlot = slot == inLLWaferStatus.inSlot[0] ? inLLWaferStatus.inSlot[1] : inLLWaferStatus.inSlot[0];                                            swapActions.Add(new MoveItem(inLL, remainSlot, ModuleName.TMRobot, 1, Hand.Blade2));                                            _tmSchdActions.Enqueue(swapActions);                                            llWafer.RouteTo(ModuleName.TMRobot, 0);                                            if (_dictModuleTask[llWafer.destMod].TimeToReady <= 30)                                            {                                                llWafer.RouteTo(llWafer.destMod, 0);                                                _tmSchdActions.Enqueue(new List<MoveItem> { new MoveItem(ModuleName.TMRobot, 0, llWafer.destMod, 0, Hand.Blade1) });                                            }                                            return;                                        }                                    }                                }                            }                        }                        else                        {                            var llWafer = _lstWaferTasks.Find(wt => wt.currentMod == inLL && wt.currentSlot == inLLWaferStatus.inSlot.First());                            if (llWafer != null)                            {                                _tmSchdActions.Enqueue(new List<MoveItem> { new MoveItem(inLL, inLLWaferStatus.inSlot.First(), ModuleName.TMRobot, 0, Hand.Blade1) });                                if (!_lstWaferTasks.Exists(wt => wt.currentMod == llWafer.destMod) && _dictModuleTask[llWafer.destMod].TimeToReady < 15)                                {                                    llWafer.RouteTo(llWafer.destMod, 0);                                    _tmSchdActions.Enqueue(new List<MoveItem> { new MoveItem(ModuleName.TMRobot, 0, llWafer.destMod, 0, Hand.Blade1) });                                }                            }                        }                    }                    if (_tmSchdActions.Count > 0)                        return;                    if(!IsLLReservedByEFEM(outLL) && outLLWaferStatus.emptySlot.Count > 0 && readyOutWafers.Count > 0)                    {                        if(readyOutWafers.Count >= 2 && outLLWaferStatus.emptySlot.Count == 2)                        {                            readyOutWafers[0].RouteTo(outLL, outLLWaferStatus.emptySlot[0]);                            readyOutWafers[1].RouteTo(outLL, outLLWaferStatus.emptySlot[1]);                            _tmSchdActions.Enqueue(new List<MoveItem> { new MoveItem(readyOutWafers[0].currentMod, readyOutWafers[0].currentSlot, ModuleName.TMRobot, 0, Hand.Blade1) });                            _tmSchdActions.Enqueue(new List<MoveItem> { new MoveItem(readyOutWafers[1].currentMod, readyOutWafers[1].currentSlot, ModuleName.TMRobot, 1, Hand.Blade2) });                            var swapActions = new List<MoveItem>();                            swapActions.Add(new MoveItem(ModuleName.TMRobot, 0, outLL, outLLWaferStatus.emptySlot[0], Hand.Blade1));                            swapActions.Add(new MoveItem(ModuleName.TMRobot, 1, outLL, outLLWaferStatus.emptySlot[1], Hand.Blade2));                            _tmSchdActions.Enqueue(swapActions);                        }                        else                        {                            var freeHands = GetTMValidFreeHands(robotWafers, new List<MoveItem>());                            readyOutWafers[0].RouteTo(outLL, outLLWaferStatus.emptySlot[0]);                            _tmSchdActions.Enqueue(new List<MoveItem> { new MoveItem(readyOutWafers[0].currentMod, readyOutWafers[0].currentSlot, ModuleName.TMRobot, (int)freeHands[0], freeHands[0]) });                            _tmSchdActions.Enqueue(new List<MoveItem> { new MoveItem(ModuleName.TMRobot, (int)freeHands[0], outLL, outLLWaferStatus.emptySlot[0], freeHands[0]) });                        }                    }                }            }            else            {                if (robotWafers.Count == 2)                {                    foreach (var wafer in robotWafers)                    {                        if (wafer.movingStatus == RState.End &&                            ModuleHelper.IsPm(wafer.destMod) &&                            _dictModuleTask[wafer.destMod].TimeToReady == 0 &&                            !_lstWaferTasks.Exists(waferT => waferT.currentMod == wafer.destMod) &&                            !_lstWaferTasks.Exists(waferT => waferT.routedMod == wafer.destMod))                        {                            wafer.RouteTo(wafer.destMod, 0);                            _tmSchdActions.Enqueue(new List<MoveItem> { new MoveItem(ModuleName.TMRobot, wafer.currentSlot, wafer.destMod, 0, (Hand)wafer.currentSlot) });                        }                    }                    if (_tmSchdActions.Count == 0)                    {                        var swapActions = FindBestLLSwapPlan(ModuleName.System, robotWafers);                        if (swapActions.llPath != ModuleName.System && swapActions.swapActions.Count > 0)                        {                            RoutingTMSwapActions(swapActions.swapActions);                            _tmSchdActions.Enqueue(swapActions.swapActions);                        }                    }                }                else if (robotWafers.Count == 1)                {                    if (ModuleHelper.IsPm(robotWafers[0].destMod) && _dictModuleTask[robotWafers[0].destMod].TimeToReady == 0)                    {                        var pmActions = new List<MoveItem>();                        var pmWafer = _lstWaferTasks.Find(wafer => (wafer.movingStatus == RState.End || wafer.movingStatus == RState.Init) && wafer.currentMod == robotWafers[0].destMod && ModuleHelper.IsLoadPort(wafer.destMod));                        if (pmWafer != null && string.IsNullOrWhiteSpace(pmWafer.wtwCleanRecipe))                        {                            int pickSlot = 1 - robotWafers[0].currentSlot;                            pmWafer.RouteTo(ModuleName.TMRobot, pickSlot);                            pmActions.Add(new MoveItem(pmWafer.currentMod, 0, ModuleName.TMRobot, pickSlot, (Hand)pickSlot));                            pmActions.Add(new MoveItem(ModuleName.TMRobot, robotWafers[0].currentSlot, pmWafer.currentMod, 0, (Hand)robotWafers[0].currentSlot));                            _tmSchdActions.Enqueue(pmActions);                            return;                        }                        if (!_lstWaferTasks.Exists(wafer => wafer.currentMod == robotWafers[0].destMod))                        {                            robotWafers[0].RouteTo(robotWafers[0].destMod, 0);                            pmActions.Add(new MoveItem(ModuleName.TMRobot, robotWafers[0].currentSlot, robotWafers[0].destMod, 0, (Hand)robotWafers[0].currentSlot));                            _tmSchdActions.Enqueue(pmActions);                            return;                        }                    }                    // try to pick a wafer from LL                    if (_tmSchdActions.Count == 0)                    {                        var swapActions = FindBestLLSwapPlan(ModuleName.System, robotWafers);                        if (swapActions.llPath != ModuleName.System && swapActions.swapActions.Count > 0)                        {                            RoutingTMSwapActions(swapActions.swapActions);                            _tmSchdActions.Enqueue(swapActions.swapActions);                            return;                        }                    }                    // try to return a wafer from PM                    var freeHand = GetTMValidFreeHands(robotWafers, new List<MoveItem>());                    var moveActions = FindBestReturnWafersPlan(freeHand.ToArray());                    if (moveActions.pmWafers.Count > 0)                    {                        MoveItem placeAction = moveActions.swapAction.Find(ac => ModuleHelper.IsLoadLock(ac.DestinationModule));                        moveActions.pmWafers.First().RouteTo(placeAction.DestinationModule, placeAction.DestinationSlot);                        _tmSchdActions.Enqueue(new List<MoveItem> { new MoveItem(moveActions.pmWafers.First().currentMod, 0, ModuleName.TMRobot, (int)freeHand[0], freeHand[0]) });                        MoveItem pickAction = moveActions.swapAction.Find(ac => ModuleHelper.IsLoadLock(ac.SourceModule));                        if (pickAction != null)                        {                            var pickWafer = _lstWaferTasks.Find(wafer => wafer.currentMod == pickAction.SourceModule && wafer.currentSlot == pickAction.SourceSlot);                            pickWafer.RouteTo(pickAction.DestinationModule, pickAction.DestinationSlot);                        }                        _tmSchdActions.Enqueue(moveActions.swapAction);                    }                }                else  // robot arm is empty                {                    // try return wafers from PM                    var freeHand = GetTMValidFreeHands(robotWafers, new List<MoveItem>());                    var moveActions = FindBestReturnWafersPlan(freeHand.ToArray());                    if (moveActions.pmWafers.Count > 0)                    {                        int handIndex = 0;                        var placeActions = moveActions.swapAction.Where(ac => ModuleHelper.IsLoadLock(ac.DestinationModule));                        foreach (var action in placeActions)                        {                            moveActions.pmWafers[handIndex].RouteTo(action.DestinationModule, action.DestinationSlot);                            _tmSchdActions.Enqueue(new List<MoveItem> { new MoveItem(moveActions.pmWafers[handIndex].currentMod, 0, ModuleName.TMRobot, (int)freeHand[handIndex], freeHand[handIndex]) });                            handIndex++;                        }                        var pickActions = moveActions.swapAction.Where(ac => ModuleHelper.IsLoadLock(ac.SourceModule)).ToList();                        foreach (var ac in pickActions)                        {                            var llWafer = _lstWaferTasks.Find(wafer => wafer.currentMod == ac.SourceModule && wafer.currentSlot == ac.SourceSlot);                            llWafer.RouteTo(ac.DestinationModule, ac.DestinationSlot);                        }                        _tmSchdActions.Enqueue(moveActions.swapAction);                    }                    if (_tmSchdActions.Count == 0)                    {                        var swapActions = FindBestLLSwapPlan(ModuleName.System, robotWafers);                        if (swapActions.llPath != ModuleName.System && swapActions.swapActions.Count > 0)                        {                            RoutingTMSwapActions(swapActions.swapActions);                            _tmSchdActions.Enqueue(swapActions.swapActions);                        }                    }                }            }        }        private void Routing4SlotVacSystem()        {            var robotWafers = _lstWaferTasks.Where(wafer => (wafer.movingStatus == RState.End || wafer.movingStatus == RState.Init) && ModuleHelper.IsTMRobot(wafer.currentMod)).OrderBy(wafer => TimeForNextModuleReady(wafer)).ToList();            if (robotWafers.Count == 2)            {                foreach (var wafer in robotWafers)                {                    if (wafer.movingStatus == RState.End &&                        ModuleHelper.IsPm(wafer.destMod) &&                        _dictModuleTask[wafer.destMod].TimeToReady == 0 &&                        !_lstWaferTasks.Exists(waferT => waferT.currentMod == wafer.destMod) &&                        !_lstWaferTasks.Exists(waferT => waferT.routedMod == wafer.destMod))                    {                        wafer.RouteTo(wafer.destMod, 0);                        _tmSchdActions.Enqueue(new List<MoveItem> { new MoveItem(ModuleName.TMRobot, wafer.currentSlot, wafer.destMod, 0, (Hand)wafer.currentSlot) });                    }                }                if (_tmSchdActions.Count == 0)                {                    var swapActions = FindBestLLSwapPlan(ModuleName.System, robotWafers);                    if (swapActions.llPath != ModuleName.System && swapActions.swapActions.Count > 0)                    {                        RoutingTMSwapActions(swapActions.swapActions);                        _tmSchdActions.Enqueue(swapActions.swapActions);                    }                }            }            else if (robotWafers.Count == 1)            {                if (ModuleHelper.IsPm(robotWafers[0].destMod) && _dictModuleTask[robotWafers[0].destMod].TimeToReady == 0)                {                    var pmActions = new List<MoveItem>();                    var pmWafer = _lstWaferTasks.Find(wafer => (wafer.movingStatus == RState.End || wafer.movingStatus == RState.Init) && wafer.currentMod == robotWafers[0].destMod && ModuleHelper.IsLoadPort(wafer.destMod));                    if (pmWafer != null && string.IsNullOrWhiteSpace(pmWafer.wtwCleanRecipe))                    {                        int pickSlot = 1 - robotWafers[0].currentSlot;                        pmWafer.RouteTo(ModuleName.TMRobot, pickSlot);                        pmActions.Add(new MoveItem(pmWafer.currentMod, 0, ModuleName.TMRobot, pickSlot, (Hand)pickSlot));                        pmActions.Add(new MoveItem(ModuleName.TMRobot, robotWafers[0].currentSlot, pmWafer.currentMod, 0, (Hand)robotWafers[0].currentSlot));                        _tmSchdActions.Enqueue(pmActions);                        return;                    }                    if (!_lstWaferTasks.Exists(wafer => wafer.currentMod == robotWafers[0].destMod))                    {                        robotWafers[0].RouteTo(robotWafers[0].destMod, 0);                        pmActions.Add(new MoveItem(ModuleName.TMRobot, robotWafers[0].currentSlot, robotWafers[0].destMod, 0, (Hand)robotWafers[0].currentSlot));                        _tmSchdActions.Enqueue(pmActions);                        return;                    }                }                // try to pick a wafer from LL                if (_tmSchdActions.Count == 0)                {                    var swapActions = FindBestLLSwapPlan(ModuleName.System, robotWafers);                    if (swapActions.llPath != ModuleName.System && swapActions.swapActions.Count > 0)                    {                        RoutingTMSwapActions(swapActions.swapActions);                        _tmSchdActions.Enqueue(swapActions.swapActions);                        return;                    }                }                // try to return a wafer from PM                var freeHand = GetTMValidFreeHands(robotWafers, new List<MoveItem>());                var moveActions = FindBestReturnWafersPlan(freeHand.ToArray());                if (moveActions.pmWafers.Count > 0)                {                    MoveItem placeAction = moveActions.swapAction.Find(ac => ModuleHelper.IsLoadLock(ac.DestinationModule));                    moveActions.pmWafers.First().RouteTo(placeAction.DestinationModule, placeAction.DestinationSlot);                    _tmSchdActions.Enqueue(new List<MoveItem> { new MoveItem(moveActions.pmWafers.First().currentMod, 0, ModuleName.TMRobot, (int)freeHand[0], freeHand[0]) });                    MoveItem pickAction = moveActions.swapAction.Find(ac => ModuleHelper.IsLoadLock(ac.SourceModule));                    if (pickAction != null)                    {                        var pickWafer = _lstWaferTasks.Find(wafer => wafer.currentMod == pickAction.SourceModule && wafer.currentSlot == pickAction.SourceSlot);                        pickWafer.RouteTo(pickAction.DestinationModule, pickAction.DestinationSlot);                    }                    _tmSchdActions.Enqueue(moveActions.swapAction);                }            }            else  // robot arm is empty            {                // try return wafers from PM                var freeHand = GetTMValidFreeHands(robotWafers, new List<MoveItem>());                var moveActions = FindBestReturnWafersPlan(freeHand.ToArray());                if (moveActions.pmWafers.Count > 0)                {                    int handIndex = 0;                    var placeActions = moveActions.swapAction.Where(ac => ModuleHelper.IsLoadLock(ac.DestinationModule));                    foreach (var action in placeActions)                    {                        moveActions.pmWafers[handIndex].RouteTo(action.DestinationModule, action.DestinationSlot);                        _tmSchdActions.Enqueue(new List<MoveItem> { new MoveItem(moveActions.pmWafers[handIndex].currentMod, 0, ModuleName.TMRobot, (int)freeHand[handIndex], freeHand[handIndex]) });                        handIndex++;                    }                    var pickActions = moveActions.swapAction.Where(ac => ModuleHelper.IsLoadLock(ac.SourceModule)).ToList();                    foreach (var ac in pickActions)                    {                        var llWafer = _lstWaferTasks.Find(wafer => wafer.currentMod == ac.SourceModule && wafer.currentSlot == ac.SourceSlot);                        llWafer.RouteTo(ac.DestinationModule, ac.DestinationSlot);                    }                    _tmSchdActions.Enqueue(moveActions.swapAction);                }                if (_tmSchdActions.Count == 0)                {                    var swapActions = FindBestLLSwapPlan(ModuleName.System, robotWafers);                    if (swapActions.llPath != ModuleName.System && swapActions.swapActions.Count > 0)                    {                        RoutingTMSwapActions(swapActions.swapActions);                        _tmSchdActions.Enqueue(swapActions.swapActions);                    }                }            }        }        private void RoutingFixedSlotVacSystem()        {            var robotWafers = _lstWaferTasks.Where(wt => ModuleHelper.IsTMRobot(wt.currentMod));            var lls = _dictModuleTask.Where(mod => ModuleHelper.IsLoadLock(mod.Key) && mod.Value.Scheduler.IsOnline);            if (_LLASlotNumber == 2)            {                if (robotWafers.Count() == 1)                {                    if(ModuleHelper.IsPm(robotWafers.First().destMod))                    {                        var destPM = robotWafers.First().destMod;                        if(_dictModuleTask[destPM].TimeToReady <= 5)                        {                            if(_lstWaferTasks.Exists(wt => wt.currentMod == destPM))                            {                                var pickHand = SelectTMPickArm(destPM);                                if(pickHand != Hand.None)                                {                                    var pmSwap = new List<MoveItem>();                                    pmSwap.Add(new MoveItem(destPM, 0, ModuleName.TMRobot, (int)pickHand, pickHand));                                    pmSwap.Add(new MoveItem(ModuleName.TMRobot, robotWafers.First().currentSlot, destPM, 0, (Hand)robotWafers.First().currentSlot));                                    _tmSchdActions.Enqueue(pmSwap);                                    return;                                }                                                            }                            else                            {                                _tmSchdActions.Enqueue(new List<MoveItem> { new MoveItem(ModuleName.TMRobot, robotWafers.First().currentSlot, destPM, 0, (Hand)robotWafers.First().currentSlot) });                                return;                            }                        }                    }                    else                    {                        var readySwapLL = lls.Where(ll => CanWaferGotoLL(robotWafers.First(), ll.Key) &&                            GetLLFixedReadyInOutSlots(ll.Key).tOutSlot.Count == 1 &&                            GetLLFixedReadyInOutSlots(ll.Key).tInSlot.Count == 1 &&                            ll.Value.TimeToReady <= 10);                        if (readySwapLL.Count() > 0)                        {                            var destLL = readySwapLL.First().Key;                            Hand pickHand = SelectTMPickArm(destLL);                            if (pickHand != Hand.None)                            {                                Hand placeHand = (Hand)robotWafers.First().currentSlot;                                var llSwap = new List<MoveItem>();                                var llSlots = GetLLFixedReadyInOutSlots(destLL);                                llSwap.Add(new MoveItem(destLL, llSlots.tOutSlot.First(), ModuleName.TMRobot, (int)pickHand, pickHand));                                llSwap.Add(new MoveItem(ModuleName.TMRobot, (int)placeHand, destLL, llSlots.tInSlot.First(), placeHand));                                _tmSchdActions.Enqueue(llSwap);                                return;                            }                        }                        var emptyLL = lls.Where(ll => CanWaferGotoLL(robotWafers.First(), ll.Key) &&                                                        GetLLFixedReadyInOutSlots(ll.Key).tInSlot.Count == 1 &&                                                        ll.Value.TimeToReady <= 2);                        if (emptyLL.Count() > 0)                        {                            var destLL = emptyLL.First().Key;                            _tmSchdActions.Enqueue(new List<MoveItem> { new MoveItem( ModuleName.TMRobot,                                                                                            robotWafers.First().currentSlot,                                                                                            destLL,                                                                                            GetLLFixedReadyInOutSlots(destLL).tInSlot.First(),                                                                                            (Hand)robotWafers.First().currentSlot) });                            return;                        }                    }                    // try to return a wafer                     var readyReturnWafers = _lstWaferTasks.Where(wt => ModuleHelper.IsPm(wt.currentMod) && ModuleHelper.IsLoadPort(wt.destMod) && _dictModuleTask[wt.currentMod].TimeToReady <= 2);                    foreach(var pmWafer in readyReturnWafers)                    {                        var readyLL = lls.Where(ll => CanWaferGotoLL(pmWafer, ll.Key) && GetLLFixedReadyInOutSlots(ll.Key).tInSlot.Count > 0 && ll.Value.TimeToReady <= 2).OrderBy(ll => ll.Value.Scheduler.IsVac ? 0 : 1);                        if(readyLL.Count() > 0)                        {                            var validHand = (Hand)(1 - robotWafers.First().currentSlot);                            _tmSchdActions.Enqueue(new List<MoveItem> { new MoveItem(pmWafer.currentMod, 0, ModuleName.TMRobot, (int)validHand, validHand) });                            _tmSchdActions.Enqueue(new List<MoveItem> { new MoveItem(ModuleName.TMRobot, (int)validHand , readyLL.First().Key, GetLLFixedReadyInOutSlots(readyLL.First().Key).tInSlot.First(), validHand) });                            return;                        }                    }                    // try to push in a wafer                     var readyInLL = lls.Where(ll => GetLLFixedReadyInOutSlots(ll.Key).tOutSlot.Count > 0 && ll.Value.TimeToReady <= 2).OrderBy(ll => ll.Value.Scheduler.IsVac ? 0 : 1);                    foreach(var ll in readyInLL)                    {                        var waferStatus = GetLLFixedReadyInOutSlots(ll.Key);                        var wafer = _lstWaferTasks.Find(wt => wt.currentMod == ll.Key && wt.currentSlot == waferStatus.tOutSlot.First());                        if( wafer != null &&                             ModuleHelper.IsPm(wafer.destMod) &&                             !_lstWaferTasks.Exists(wt => wt.currentMod == wafer.destMod) &&                             _dictModuleTask[wafer.destMod].TimeToReady <= 2)                        {                            var validHand = (Hand)(1 - robotWafers.First().currentSlot);                            _tmSchdActions.Enqueue(new List<MoveItem> { new MoveItem(wafer.currentMod, wafer.currentSlot, ModuleName.TMRobot, (int)validHand, validHand) });                            _tmSchdActions.Enqueue(new List<MoveItem> { new MoveItem(ModuleName.TMRobot, (int)validHand, wafer.destMod, 0, validHand) });                            return;                        }                    }                }                else if (robotWafers.Count() == 0)                {                    var readyReturnWafers = _lstWaferTasks.Where(wt => ModuleHelper.IsPm(wt.currentMod) && ModuleHelper.IsLoadPort(wt.destMod)).ToList();                    if(readyReturnWafers.Count > 0)                    {                        // try to do a LL swap action                        var readySwapLL = lls.Where(ll => GetLLFixedReadyInOutSlots(ll.Key).tOutSlot.Count == 1 && GetLLFixedReadyInOutSlots(ll.Key).tInSlot.Count == 1 && ll.Value.TimeToReady <= 10);                        foreach (var pmWafer in readyReturnWafers)                        {                            foreach (var ll in readySwapLL)                            {                                if (CanWaferGotoLL(pmWafer, ll.Key))                                {                                    var returnHand = SelectTMPickArm(pmWafer.currentMod);                                    var pickHand = SelectTMPickArm(ll.Key);                                    var llWaferStatus = GetLLFixedReadyInOutSlots(ll.Key);                                    _tmSchdActions.Enqueue(new List<MoveItem> { new MoveItem(pmWafer.currentMod, pmWafer.currentSlot, ModuleName.TMRobot, (int)returnHand, returnHand) });                                    var llSwapActions = new List<MoveItem>();                                    llSwapActions.Add(new MoveItem(ModuleName.TMRobot, (int)returnHand, ll.Key, llWaferStatus.tInSlot.First(), returnHand));                                    llSwapActions.Add(new MoveItem(ll.Key, llWaferStatus.tOutSlot.First(), ModuleName.TMRobot, (int)pickHand, pickHand));                                    _tmSchdActions.Enqueue(llSwapActions);                                    return;                                }                            }                        }                        // just return to LL                        var readyInLL = lls.Where(ll => GetLLFixedReadyInOutSlots(ll.Key).tInSlot.Count == 1 && ll.Value.TimeToReady <= 5);                        foreach(var pmWafer in readyReturnWafers)                        {                            foreach(var ll in readyInLL)                            {                                if(CanWaferGotoLL(pmWafer, ll.Key))                                {                                    var returnHand = SelectTMPickArm(pmWafer.currentMod);                                    _tmSchdActions.Enqueue(new List<MoveItem> { new MoveItem(pmWafer.currentMod, pmWafer.currentSlot, ModuleName.TMRobot, (int)returnHand, returnHand) });                                    _tmSchdActions.Enqueue(new List<MoveItem> { new MoveItem(ModuleName.TMRobot, (int)returnHand, ll.Key, GetLLFixedReadyInOutSlots(ll.Key).tInSlot.First(), returnHand) });                                    return;                                }                            }                        }                    }                    var readyPushInLLs = lls.Where(ll => GetLLFixedReadyInOutSlots(ll.Key).tOutSlot.Count == 1 && ll.Value.TimeToReady <= 2);                    if(readyPushInLLs.Count() > 0)                    {                        var destLL = readyPushInLLs.First().Key;                        if(readyPushInLLs.Count() == 2 && readyPushInLLs.First().Value.Scheduler.IsAtm && readyPushInLLs.Last().Value.Scheduler.IsVac)                        {                            destLL = readyPushInLLs.Last().Key;                        }                        var pickHand = SelectTMPickArm(destLL);                        _tmSchdActions.Enqueue(new List<MoveItem> { new MoveItem(destLL, GetLLFixedReadyInOutSlots(destLL).tOutSlot.First(), ModuleName.TMRobot, (int)pickHand, pickHand) });                        return;                    }                }                else                {                    // should not go here                    LOG.Write(eEvent.WARN_ROUTER, ModuleName.System, "Had better avoid picking two wafers on TM robot arms under Loadlock fixed slot pattern");                    foreach(var wafer in robotWafers)                    {                        if(ModuleHelper.IsPm(wafer.destMod))                        {                            if(!_lstWaferTasks.Exists(wt => wt.currentMod == wafer.destMod) && _dictModuleTask[wafer.destMod].TimeToReady  <= 2)                            {                                _tmSchdActions.Enqueue(new List<MoveItem> { new MoveItem(ModuleName.TMRobot, wafer.currentSlot, wafer.destMod, 0, (Hand)wafer.currentSlot) });                                return;                            }                        }                        else                        {                            var readyInLL = lls.Where(ll => GetLLFixedReadyInOutSlots(ll.Key).tInSlot.Count == 1 && CanWaferGotoLL(wafer, ll.Key) && ll.Value.TimeToReady <= 2);                            if(readyInLL.Count() > 0)                            {                                _tmSchdActions.Enqueue(new List<MoveItem> { new MoveItem(ModuleName.TMRobot, wafer.currentSlot, readyInLL.First().Key, GetLLFixedReadyInOutSlots(readyInLL.First().Key).tInSlot.First(), (Hand)wafer.currentSlot) });                                return;                            }                        }                    }                }            }            else //  4 slot Loadlock            {                if(robotWafers.Count() > 0)                {                    if (robotWafers.Count() == 2)                    {                        if (robotWafers.All(wt => ModuleHelper.IsLoadPort(wt.destMod)))                        {                            var destLL = lls.Where(ll => robotWafers.All(wt => CanWaferGotoLL(wt, ll.Key)) &&                                                    ll.Value.TimeToReady <= 10 &&                                                    GetLLFixedReadyInOutSlots(ll.Key).tInSlot.Count == 2).                                                    OrderByDescending(ll => GetLLFixedReadyInOutSlots(ll.Key).tOutSlot.Count).                                                    OrderBy(ll => ll.Value.TimeToReady);                            if (destLL.Count() > 0)                            {                                var swapLL = destLL.First().Key;                                var llWaferStatus = GetLLFixedReadyInOutSlots(swapLL);                                var swapActions = new List<MoveItem>();                                swapActions.Add(new MoveItem(ModuleName.TMRobot, robotWafers.First().currentSlot, swapLL, llWaferStatus.tInSlot.First(), (Hand)robotWafers.First().currentSlot));                                swapActions.Add(new MoveItem(ModuleName.TMRobot, robotWafers.Last().currentSlot, swapLL, llWaferStatus.tInSlot.Last(), (Hand)robotWafers.Last().currentSlot));                                int pickCount = 0;                                foreach (var slot in llWaferStatus.eOutSlot)                                {                                    swapActions.Add(new MoveItem(swapLL, slot, ModuleName.TMRobot, pickCount, (Hand)pickCount));                                }                                _tmSchdActions.Enqueue(swapActions);                                return;                            }                        }                        foreach (var wafer in robotWafers)                        {                            if (ModuleHelper.IsPm(wafer.destMod))                            {                                if (!_lstWaferTasks.Exists(wt => wt.currentMod == wafer.destMod) && _dictModuleTask[wafer.destMod].TimeToReady <= 5)                                {                                    _tmSchdActions.Enqueue(new List<MoveItem> { new MoveItem(ModuleName.TMRobot, wafer.currentSlot, wafer.destMod, 0, (Hand)wafer.currentSlot) });                                    return;                                }                            }                            else                            {                                var placeLL = lls.Where(ll => CanWaferGotoLL(wafer, ll.Key) && ll.Value.TimeToReady <= 5 && GetLLFixedReadyInOutSlots(ll.Key).tInSlot.Count > 0).OrderBy(ll => ll.Value.TimeToReady);                                if (placeLL.Count() > 0)                                {                                    _tmSchdActions.Enqueue(new List<MoveItem> { new MoveItem(ModuleName.TMRobot, wafer.currentSlot, placeLL.First().Key, GetLLFixedReadyInOutSlots(placeLL.First().Key).tInSlot.First(), (Hand)wafer.currentSlot) });                                    return;                                }                            }                        }                    }                    else if (robotWafers.Count() == 1)                    {                        var robotWafer = robotWafers.First();                        if (ModuleHelper.IsPm(robotWafer.destMod))                        {                            if (_dictModuleTask[robotWafer.destMod].TimeToReady <= 5)                            {                                if (_lstWaferTasks.Exists(wt => wt.currentMod == robotWafer.destMod))                                {                                    var pmSwap = new List<MoveItem>();                                    pmSwap.Add(new MoveItem(robotWafer.destMod, 0, ModuleName.TMRobot, 1 - robotWafer.currentSlot, (Hand)(1 - robotWafer.currentSlot)));                                    pmSwap.Add(new MoveItem(ModuleName.TMRobot, robotWafer.currentSlot, robotWafer.destMod, 0, (Hand)robotWafer.currentSlot));                                    _tmSchdActions.Enqueue(pmSwap);                                    return;                                }                                else                                {                                    _tmSchdActions.Enqueue(new List<MoveItem> { new MoveItem(ModuleName.TMRobot, robotWafer.currentSlot, robotWafer.destMod, 0, (Hand)robotWafer.currentSlot) });                                    return;                                }                            }                        }                        else                        {                            var destLL = lls.Where(ll => CanWaferGotoLL(robotWafer, ll.Key) &&                                                    ll.Value.TimeToReady <= 10 &&                                                    GetLLFixedReadyInOutSlots(ll.Key).tInSlot.Count > 0).                                                    OrderByDescending(ll => GetLLFixedReadyInOutSlots(ll.Key).tOutSlot.Count).                                                    OrderBy(ll => ll.Value.TimeToReady);                            if (destLL.Count() > 0)                            {                                var swapLL = destLL.First().Key;                                var llWaferStatus = GetLLFixedReadyInOutSlots(swapLL);                                var llSwap = new List<MoveItem>();                                llSwap.Add(new MoveItem(ModuleName.TMRobot, robotWafer.currentSlot, swapLL, llWaferStatus.tInSlot.First(), (Hand)robotWafer.currentSlot));                                int pickCount = 0;                                foreach (var slot in llWaferStatus.tOutSlot)                                {                                    llSwap.Add(new MoveItem(swapLL, slot, ModuleName.TMRobot, pickCount, (Hand)pickCount));                                    pickCount++;                                }                                _tmSchdActions.Enqueue(llSwap);                                return;                            }                        }                        // try to return a wafer                         var readyReturnWafers = _lstWaferTasks.Where(wt => ModuleHelper.IsPm(wt.currentMod) && ModuleHelper.IsLoadPort(wt.destMod) && _dictModuleTask[wt.currentMod].TimeToReady <= 2);                        foreach (var pmWafer in readyReturnWafers)                        {                            var readyLL = lls.Where(ll => CanWaferGotoLL(pmWafer, ll.Key) && GetLLFixedReadyInOutSlots(ll.Key).tInSlot.Count > 0 && ll.Value.TimeToReady <= 2).OrderBy(ll => ll.Value.Scheduler.IsVac ? 0 : 1);                            if (readyLL.Count() > 0)                            {                                var validHand = (Hand)(1 - robotWafers.First().currentSlot);                                _tmSchdActions.Enqueue(new List<MoveItem> { new MoveItem(pmWafer.currentMod, 0, ModuleName.TMRobot, (int)validHand, validHand) });                                _tmSchdActions.Enqueue(new List<MoveItem> { new MoveItem(ModuleName.TMRobot, (int)validHand, readyLL.First().Key, GetLLFixedReadyInOutSlots(readyLL.First().Key).tInSlot.First(), validHand) });                                return;                            }                        }                        // try to push in a wafer                         var readyInLL = lls.Where(ll => GetLLFixedReadyInOutSlots(ll.Key).tOutSlot.Count > 0 && ll.Value.TimeToReady <= 2).OrderBy(ll => ll.Value.Scheduler.IsVac ? 0 : 1);                        foreach (var ll in readyInLL)                        {                            var waferStatus = GetLLFixedReadyInOutSlots(ll.Key);                            var wafer = _lstWaferTasks.Find(wt => wt.currentMod == ll.Key && wt.currentSlot == waferStatus.tOutSlot.First());                            if (wafer != null &&                                ModuleHelper.IsPm(wafer.destMod) &&                                !_lstWaferTasks.Exists(wt => wt.currentMod == wafer.destMod) &&                                _dictModuleTask[wafer.destMod].TimeToReady <= 2)                            {                                var validHand = (Hand)(1 - robotWafers.First().currentSlot);                                _tmSchdActions.Enqueue(new List<MoveItem> { new MoveItem(wafer.currentMod, wafer.currentSlot, ModuleName.TMRobot, (int)validHand, validHand) });                                _tmSchdActions.Enqueue(new List<MoveItem> { new MoveItem(ModuleName.TMRobot, (int)validHand, wafer.destMod, 0, validHand) });                                return;                            }                        }                    }                }                else // robot empty                {                    var nearlyReadyReturnWafers = _lstWaferTasks.Where(wt => ModuleHelper.IsPm(wt.currentMod) && (ModuleHelper.IsLoadPort(wt.destMod) || _dictModuleTask[wt.currentMod].TimeToReady <= 10)).OrderBy(wt => _dictModuleTask[wt.currentMod].TimeToReady).ToList();                    var readyLL = lls.Where(ll => ll.Value.TimeToReady <= 10);                    if(readyLL.Count() > 0)                    {                        var llPath = FindTheBestMovePathWithFixSlot(readyLL, nearlyReadyReturnWafers);                        if(ModuleHelper.IsLoadLock(llPath))                        {                            int returnCount = 0;                            var llWaferStatus = GetLLFixedReadyInOutSlots(llPath);                            var llSwapActions = new List<MoveItem>();                            foreach(var wafer in nearlyReadyReturnWafers)                            {                                if(CanWaferGotoLL(wafer, llPath) && returnCount < Math.Min(llWaferStatus.tInSlot.Count, 2))                                {                                    _tmSchdActions.Enqueue(new List<MoveItem> { new MoveItem(wafer.currentMod, 0, ModuleName.TMRobot, returnCount, (Hand)returnCount) });                                    llSwapActions.Add(new MoveItem(ModuleName.TMRobot, returnCount, llPath, llWaferStatus.tInSlot[returnCount], (Hand)returnCount));                                    returnCount++;                                }                            }                            int pickCount = 0;                            foreach(var slot in llWaferStatus.tOutSlot)                            {                                if (pickCount < 2)                                {                                    llSwapActions.Add(new MoveItem(llPath, slot, ModuleName.TMRobot, pickCount, (Hand)pickCount));                                    pickCount++;                                }                            }                            if(llSwapActions.Count > 0)                            {                                _tmSchdActions.Enqueue(llSwapActions);                            }                            return;                        }                    }                }            }        }        private bool IsTMRobotArmNotReserved(Hand hand)        {            if (WaferManager.Instance.CheckHasWafer(ModuleName.TMRobot, (int)hand) || _lstWaferTasks.Exists(wt => wt.currentMod == ModuleName.TMRobot && wt.currentSlot == (int)hand))                return false;            foreach(var acs in _tmSchdActions)            {                foreach(var ac in acs)                {                    if ((ac.DestinationModule == ModuleName.TMRobot || ac.SourceModule == ModuleName.TMRobot) && ac.DestinationSlot == (int)hand)                        return false;                }            }            return true;        }        private Hand SelectTMPickArm(ModuleName mod)        {            switch (_tmRobotSingleArmOption)            {                case 0:                    {                        if (IsTMRobotArmNotReserved(Hand.Blade1))                            return Hand.Blade1;                        if (IsTMRobotArmNotReserved(Hand.Blade2))                            return Hand.Blade2;                    }                    break;                case 1:                    {                        if (IsTMRobotArmNotReserved(Hand.Blade1))                            return Hand.Blade1;                    }                    break;                case 2:                    {                        if (IsTMRobotArmNotReserved(Hand.Blade2))                            return Hand.Blade2;                    }                    break;                // Blade1 In Blade2 Out                case 3:                     {                        if (ModuleHelper.IsLoadLock(mod) && IsTMRobotArmNotReserved(Hand.Blade1))                            return Hand.Blade1;                        if (ModuleHelper.IsPm(mod) && IsTMRobotArmNotReserved(Hand.Blade2))                            return Hand.Blade2;                    }                    break;                // Blade2 In Blade1 Out                case 4:                    {                        if (ModuleHelper.IsLoadLock(mod) && IsTMRobotArmNotReserved(Hand.Blade2))                            return Hand.Blade2;                        if (ModuleHelper.IsPm(mod) && IsTMRobotArmNotReserved(Hand.Blade1))                            return Hand.Blade1;                    }                    break;            }            return Hand.None;        }        private List<Hand> GetTMFreeHand()        {            var lstHands = new List<Hand>();            if (WaferManager.Instance.CheckNoWafer(ModuleName.TMRobot, 0) && _tmRobotSingleArmOption != 2)                lstHands.Add(Hand.Blade1);            if (WaferManager.Instance.CheckNoWafer(ModuleName.TMRobot, 1) && _tmRobotSingleArmOption != 1)                lstHands.Add(Hand.Blade2);            return lstHands;        }        private List<Hand> GetEFEMFreeHand()        {            var lstHands = new List<Hand>();            if (WaferManager.Instance.CheckNoWafer(ModuleName.EfemRobot, 0) && _efemRobotSingleArmOption != 2)                lstHands.Add(Hand.Blade1);            if (WaferManager.Instance.CheckNoWafer(ModuleName.EfemRobot, 1) && _efemRobotSingleArmOption != 1)                lstHands.Add(Hand.Blade2);            return lstHands;        }        private bool CanWaferGotoLL(WaferTask task, ModuleName ll)        {            bool bVacWafer = ModuleHelper.IsPm(task.currentMod) || ModuleHelper.IsTMRobot(task.currentMod);            if (bVacWafer)            {                if (ModuleHelper.IsPm(task.destMod))                    return false;                switch (task.llInOutPath)                {                    case SequenceLLInOutPath.AInAOut:                    case SequenceLLInOutPath.BInAOut:                        return ll == ModuleName.LLA;                    case SequenceLLInOutPath.AInBOut:                    case SequenceLLInOutPath.BInBOut:                        return ll == ModuleName.LLB;                    case SequenceLLInOutPath.DInDOut:                        return true;                }            }            else            {                if (ModuleHelper.IsLoadPort(task.destMod))                    return false;                switch (task.llInOutPath)                {                    case SequenceLLInOutPath.AInAOut:                    case SequenceLLInOutPath.AInBOut:                        return ll == ModuleName.LLA;                    case SequenceLLInOutPath.BInAOut:                    case SequenceLLInOutPath.BInBOut:                        return ll == ModuleName.LLB;                    case SequenceLLInOutPath.DInDOut:                        return true;                }            }            return false;        }        private (List<int> inSlot, List<int> outSlot, List<int> emptySlot) GetLLReadyInOutSlots(ModuleName ll)        {            var readInSlots = new List<int>();            var readyOutSlots = new List<int>();            var emptySlots = new List<int>();            for(int slot = 0; slot < (ll == ModuleName.LLA ? _LLASlotNumber : _LLBSlotNumber); slot++)            {                if(WaferManager.Instance.CheckNoWafer(ll, slot) && !_lstWaferTasks.Exists(wafer => (wafer.routedMod == ll && wafer.routedSlot == slot) || (wafer.currentMod == ll && wafer.currentSlot == slot) || (wafer.nextMod == ll && wafer.nextSlot == slot)))                {                    emptySlots.Add(slot);                }                if(WaferManager.Instance.CheckHasWafer(ll, slot))                {                    Guid waferID = WaferManager.Instance.GetWafer(ll, slot).InnerId;                    var waferTask = _lstWaferTasks.Find(wafer => wafer.waferId == waferID);                    if(waferTask != null && waferTask.movingStatus == RState.End)                    {                        if (ModuleHelper.IsPm(waferTask.destMod))                            readInSlots.Add(slot);                        else if (_dictModuleTask[ll].Scheduler.WaferArrivedTicks(slot) > waferTask.llDelayTime * 1000)                            readyOutSlots.Add(slot);                    }                }            }            return (readInSlots, readyOutSlots, emptySlots);        }        private (List<int> eInSlot, List<int> eOutSlot, List<int> tInSlot, List<int> tOutSlot) GetLLFixedReadyInOutSlots(ModuleName ll)        {            var eInSlot = new List<int>();            var eOutSlot = new List<int>();            var tInSlot = new List<int>();            var tOutSlot = new List<int>();            int SlotNumber = ll == ModuleName.LLA ? _LLASlotNumber : _LLBSlotNumber;            for (int slot = 0; slot < SlotNumber; slot++)            {                if (WaferManager.Instance.CheckNoWafer(ll, slot) && !_lstWaferTasks.Exists(wafer => (wafer.routedMod == ll && wafer.routedSlot == slot) || (wafer.currentMod == ll && wafer.currentSlot == slot) || (wafer.nextMod == ll && wafer.nextSlot == slot)))                {                    if ((slot >= SlotNumber / 2 && _LLSlotInOutOption == LLSlotInOutOpt.UpperInLowerOut) ||                         (slot < SlotNumber / 2 && _LLSlotInOutOption == LLSlotInOutOpt.LowerInUpperOut))                    {                        eInSlot.Add(slot);                    }                    else                    {                        tInSlot.Add(slot);                    }                }                if (WaferManager.Instance.CheckHasWafer(ll, slot))                {                    var wafer = WaferManager.Instance.GetWafer(ll, slot);                    var waferTask = _lstWaferTasks.Find(wt => wt.waferId == wafer.InnerId && wt.currentMod == ll && wt.currentSlot == slot);                    if(waferTask == null)                    {                        LOG.Write(eEvent.EV_ROUTER, ll, $"Routing trace: did not find inner task associated with {wafer.WaferOrigin} at {ll}.{slot + 1}");                    }                    else if (waferTask.movingStatus == RState.End)                    {                        if (ModuleHelper.IsPm(waferTask.destMod))                            tOutSlot.Add(slot);                        else if (_dictModuleTask[ll].Scheduler.WaferArrivedTicks(slot) > waferTask.llDelayTime * 1000)                            eOutSlot.Add(slot);                    }                }            }                        return (eInSlot, eOutSlot, tInSlot, tOutSlot);        }        private (List<WaferInfo> wafers, List<int> emptySlots) GetLLWaferExistance(ModuleName ll)        {            var lstWafers = new List<WaferInfo>();            var lstEmptySlots = new List<int>();            for (int slot = 0; slot < (ll == ModuleName.LLA ? _LLASlotNumber : _LLBSlotNumber); slot++)            {                var wafer = WaferManager.Instance.GetWafer(ll, slot);                if(wafer != null && !wafer.IsEmpty)                {                    lstWafers.Add(wafer);                }                else                {                    lstEmptySlots.Add(slot);                }            }                        return (lstWafers, lstEmptySlots);        }        private void PrepareLLPressure()        {            if (RouteManager.IsATMMode)                return;            var preaparedLLs = new List<ModuleName>();            var lls = _efemSchdActions.Where(acs => ModuleHelper.IsLoadLock(acs.First().Module)).Select(item => item.First().Module).ToList();            if (_curEfemAction.Count == 0 && _efemSchdActions.Count > 0 && ModuleHelper.IsLoadLock(_efemSchdActions.First().First().Module))                lls.Remove(_efemSchdActions.First().First().Module);            foreach(var ll in lls)            {                if(_dictModuleTask[ll].Scheduler.IsAvailable && _dictModuleTask[ll].Scheduler.IsVac && !preaparedLLs.Contains(ll))                {                    (_dictModuleTask[ll].Scheduler as SchedulerLoadLock).PreVent();                    preaparedLLs.Add(ll);                }            }            lls = _tmSchdActions.Where(acs => ModuleHelper.IsLoadLock(acs.First().Module)).Select(item => item.First().Module).ToList();            if(_curTmAction.Count == 0 && _tmSchdActions.Count > 0 && ModuleHelper.IsLoadLock(_tmSchdActions.First().First().Module))                lls.Remove(_tmSchdActions.First().First().Module);            foreach (var ll in lls)            {                if (_dictModuleTask[ll].Scheduler.IsAvailable && _dictModuleTask[ll].Scheduler.IsAtm && !preaparedLLs.Contains(ll))                {                    (_dictModuleTask[ll].Scheduler as SchedulerLoadLock).PrePump();                    preaparedLLs.Add(ll);                }            }            if (_efemSchdActions.Count > 0 || _curEfemAction.Count > 0 || _tmSchdActions.Count > 0 || _curTmAction.Count > 0)                return;            if (LLInOutPath == SequenceLLInOutPath.AInBOut || LLInOutPath == SequenceLLInOutPath.BInAOut)            {                var inLL = LLInOutPath == SequenceLLInOutPath.AInBOut ? ModuleName.LLA : ModuleName.LLB;                var outLL = LLInOutPath == SequenceLLInOutPath.AInBOut ? ModuleName.LLB : ModuleName.LLA;                var inLLWaferCount = _lstWaferTasks.Where(wafer => wafer.currentMod == inLL).Count();                var outLLWaferCount = _lstWaferTasks.Where(wafer => wafer.currentMod == outLL).Count();                if (inLLWaferCount == 0 && !preaparedLLs.Contains(inLL))                {                    (_dictModuleTask[inLL] as LoadlockTask).PreVent();                    preaparedLLs.Add(inLL);                }                else if(inLLWaferCount == (LLInOutPath == SequenceLLInOutPath.AInBOut ? _LLASlotNumber : _LLBSlotNumber) && !preaparedLLs.Contains(inLL))                {                    (_dictModuleTask[inLL] as LoadlockTask).PrePump();                    preaparedLLs.Add(inLL);                }                if(outLLWaferCount == 0 && !preaparedLLs.Contains(outLL))                {                    (_dictModuleTask[outLL] as LoadlockTask).PrePump();                    preaparedLLs.Add(outLL);                }                else if(outLLWaferCount == (LLInOutPath == SequenceLLInOutPath.BInAOut ? _LLASlotNumber : _LLBSlotNumber) && !preaparedLLs.Contains(outLL))                {                    (_dictModuleTask[outLL] as LoadlockTask).PreVent();                    preaparedLLs.Add(outLL);                }            }        }        private void ReturnVacWafers()        {            if (_tmSchdActions.Count > 0 || _curTmAction.Count > 0)            {                RunSchdTMReturnActions();                return;            }            if (_tmRobotStatus != RState.End)                return;            var hands = GetTMFreeHand();            var lls = _dictModuleTask.Where(mod => ModuleHelper.IsLoadLock(mod.Key) && !IsLLReservedByEFEM(mod.Key) && mod.Value.Scheduler.IsIdle  && mod.Value.Scheduler.IsInclude && GetLLWaferExistance(mod.Key).emptySlots.Count > 0).OrderByDescending(mod => GetLLReadyInOutSlots(mod.Key).emptySlot.Count);            if(lls.Count() > 0)            {                // return robot wafers                int moveCount = 0;                var llActions = new List<MoveItem>();                var emptySlots = GetLLWaferExistance(lls.First().Key).emptySlots;                for(int arm = 0; arm < 2; arm++)                {                    var wafer = WaferManager.Instance.GetWafer(ModuleName.TMRobot, arm);                    if(wafer != null && !wafer.IsEmpty && moveCount < emptySlots.Count)                    {                        llActions.Add(new MoveItem(ModuleName.TMRobot, arm, lls.First().Key, emptySlots[moveCount], (Hand)arm));                        moveCount++;                    }                }                if(moveCount > 0)                {                    _tmSchdActions.Enqueue(llActions);                    return;                }                // return PM wafers                var PickActions = new List<MoveItem>();                var hasWaferPMs = _dictModuleTask.Where(mod => ModuleHelper.IsPm(mod.Key) && mod.Value.Scheduler.IsIdle && mod.Value.Scheduler.IsInclude && WaferManager.Instance.CheckHasWafer(mod.Key, 0));                foreach(var pm in hasWaferPMs)                {                    if (moveCount < hands.Count && moveCount < emptySlots.Count)                    {                        PickActions.Add(new MoveItem(pm.Key, 0, ModuleName.TMRobot, (int)hands[moveCount], hands[moveCount]));                        llActions.Add(new MoveItem(ModuleName.TMRobot, (int)hands[moveCount], lls.First().Key, emptySlots[moveCount], hands[moveCount]));                        moveCount++;                    }                }                if(moveCount > 0)                {                    foreach(var ac in PickActions)                    {                        _tmSchdActions.Enqueue(new List<MoveItem> { ac });                    }                    _tmSchdActions.Enqueue(llActions);                }            }        }        private void ReturnAtmWafers()        {            if (_efemSchdActions.Count > 0 || _curEfemAction.Count > 0)            {                RunSchdEFEMReturnActions();                return;            }            if (_efemRobotStatus != RState.End)                return;            // return Robot Wafer            for(int i = 0; i < 2; i++)            {                var wafer = WaferManager.Instance.GetWafer(ModuleName.EfemRobot, i);                if(wafer != null && !wafer.IsEmpty)                {                    _efemSchdActions.Enqueue(new List<MoveItem> { new MoveItem(ModuleName.EfemRobot, i, (ModuleName)wafer.OriginStation, wafer.OriginSlot, (Hand)i) });                }            }            if (_efemSchdActions.Count > 0)                return;            var hands = GetEFEMFreeHand();            // return Aligner wafer            var aligner = ModuleHelper.InstalledModules.Where(mod => ModuleHelper.IsAligner(mod)).ToList();            if(aligner.Count > 0 && WaferManager.Instance.CheckHasWafer(aligner.First(), 0) && hands.Count > 0)            {                var wafer = WaferManager.Instance.GetWafer(aligner.First(), 0);                _efemSchdActions.Enqueue(new List<MoveItem> { new MoveItem(aligner.First(), 0, ModuleName.EfemRobot, (int)hands.First(), hands.First()) });                _efemSchdActions.Enqueue(new List<MoveItem> { new MoveItem(ModuleName.EfemRobot, (int)hands.First(), (ModuleName)wafer.OriginStation, wafer.OriginSlot, hands.First()) });                return;            }            // return Loadlock wafer            var lls = _dictModuleTask.Where(mod => ModuleHelper.IsLoadLock(mod.Key) && !IsLLReservedByTM(mod.Key) && mod.Value.Scheduler.IsIdle && GetLLWaferExistance(mod.Key).wafers.Count > 0).OrderByDescending(mod => GetLLWaferExistance(mod.Key).wafers.Count);            if(lls.Count() > 0)            {                int returnCount = 0;                var llActions = new List<MoveItem>();                var placActions = new List<MoveItem>();                foreach(var wafer in GetLLWaferExistance(lls.First().Key).wafers)                {                    if(returnCount < hands.Count)                    {                        llActions.Add(new MoveItem(lls.First().Key, wafer.Slot, ModuleName.EfemRobot, (int)hands[returnCount], hands[returnCount]));                        placActions.Add(new MoveItem(ModuleName.EfemRobot, (int)hands[returnCount], (ModuleName)wafer.OriginStation, wafer.OriginSlot, hands[returnCount]));                        returnCount++;                    }                }                if (returnCount > 0)                {                    _efemSchdActions.Enqueue(llActions);                    foreach (var ac in placActions)                    {                        _efemSchdActions.Enqueue(new List<MoveItem> { ac });                    }                }            }        }        private void RunSchdEFEMReturnActions()        {            var efemRobot = Singleton<TransferModule>.Instance.GetScheduler(ModuleName.EfemRobot) as SchedulerEfemRobot;            if (efemRobot == null || !efemRobot.IsAvailable)                return;            if (_efemSchdActions.Count > 0)            {                if (_curEfemAction.Count == 0 || isReturnActionsDone(_curEfemAction))                {                    var nextActions = _efemSchdActions.First();                    var nextModule = nextActions.First().Module;                    if (ModuleHelper.IsLoadLock(nextModule) && !_dictModuleTask[nextModule].IsIdle)                        return;                    _curEfemAction = _efemSchdActions.Dequeue();                    efemRobot.PostMoveItems(_curEfemAction.ToArray());                }            }            else if (_curEfemAction.Count >= 0 && isReturnActionsDone(_curEfemAction)) // all scheduled actions done            {                _curEfemAction.Clear();            }        }        private void RunSchdTMReturnActions()        {            var tmRobot = Singleton<TransferModule>.Instance.GetScheduler(ModuleName.TMRobot) as SchedulerTMRobot;            if (tmRobot == null || !tmRobot.IsAvailable)                return;            if (_tmSchdActions.Count > 0)            {                if (_curTmAction.Count == 0 || isReturnActionsDone(_curTmAction))                {                    var nextActions = _tmSchdActions.First();                    var nextModule = nextActions.First().Module;                    if (ModuleHelper.IsLoadLock(nextModule) && !_dictModuleTask[nextModule].IsIdle)                        return;                    _curTmAction = _tmSchdActions.Dequeue();                    tmRobot.SendMoveItems(_curTmAction.ToArray());                }            }            else if (_curTmAction.Count >= 0 && isReturnActionsDone(_curTmAction)) // all scheduled actions done            {                _curTmAction.Clear();            }        }        #endregion        #region sequence/recipe operation        private bool CheckSequencePmReady(SequenceInfo seq, out string reason)        {            reason = "";            foreach(var pm in seq.PMs)            {                if (ModuleHelper.IsInstalled(pm) && (_dictModuleTask[pm].Scheduler.IsOnline || !Singleton<RouteManager>.Instance.IsAutoMode))                    return true;            }            reason = $"Sequence {seq.Name} no valid PM, " + string.Join("|", seq.PMs);            return false;        }        private bool CheckSequenceKepler2200TemperatureReady(SequenceInfo seq)        {            for (int i = 0; i < seq.Steps.Count; i++)            {                SequenceStepInfo stepInfo = seq.Steps[i];                foreach (var module in stepInfo.StepModules)                {                    if (ModuleHelper.IsPm(module))                    {                        string attr = $"{module}Recipe";                        if (stepInfo.StepParameter.ContainsKey(attr)                            && !string.IsNullOrWhiteSpace((string)stepInfo.StepParameter[attr]))                        {                            var recipeName = (string)stepInfo.StepParameter[attr];                            var recipeContent =                                    RecipeFileManager.Instance.LoadRecipe($"{module}", recipeName, false, "Process");                            var recipe = Recipe.Load(recipeContent);                            float currentChamberTemperature;                            switch (module)                            {                                case ModuleName.PMA:                                    currentChamberTemperature = Singleton<RouteManager>.Instance.PMA.ChamberTemperature;                                    break;                                case ModuleName.PMB:                                    currentChamberTemperature = Singleton<RouteManager>.Instance.PMB.ChamberTemperature;                                    break;                                case ModuleName.PMC:                                    currentChamberTemperature = Singleton<RouteManager>.Instance.PMC.ChamberTemperature;                                    break;                                case ModuleName.PMD:                                    currentChamberTemperature = Singleton<RouteManager>.Instance.PMD.ChamberTemperature;                                    break;                                default:                                    currentChamberTemperature = 0;                                    break;                            }                            if (recipe.Header.Temperature != null && recipe.Header.Temperature != "" && (currentChamberTemperature > Convert.ToSingle(recipe.Header.Temperature) + 10 || currentChamberTemperature < Convert.ToSingle(recipe.Header.Temperature) - 10))                            {                                LOG.Write(eEvent.ERR_ROUTER, ModuleName.System, $"Start job失败,由于{module}腔体温度{currentChamberTemperature}与{recipeName} Recipe温度{recipe.Header.Temperature}不匹配");                                return false;                            }                        }                    }                }            }            return true;        }        private bool CheckSequenceRecipeFileValid(SequenceInfo seq, out string reason)        {            for (int i = 0; i < seq.Steps.Count; i++)            {                SequenceStepInfo stepInfo = seq.Steps[i];                foreach (var module in stepInfo.StepModules)                {                    if (ModuleHelper.IsPm(module))                    {                        string attr = $"{module}Recipe";                        if (stepInfo.StepParameter.ContainsKey(attr)                            && !string.IsNullOrWhiteSpace((string)stepInfo.StepParameter[attr]))                        {                            var recipeName = (string)stepInfo.StepParameter[attr];                            if (!string.IsNullOrWhiteSpace(recipeName))                            {                                var recipeContent =                                    RecipeFileManager.Instance.LoadRecipe($"{module}", recipeName, false, "Process");                                if (string.IsNullOrWhiteSpace(recipeContent))                                {                                    reason = $"Can not find recipe file{recipeName}";                                    return false;                                }                            }                        }                    }                }            }            reason = "";            return true;        }        private void UpdateLLInOutPathProperty()        {            if (_lstControlJobs.Count == 0)                return;            var inOutPaths = new List<SequenceLLInOutPath>();             foreach(var wt in _lstWaferTasks)            {                if (!inOutPaths.Contains(wt.llInOutPath))                    inOutPaths.Add(wt.llInOutPath);            }            if (inOutPaths.Count == 1)            {                _LLInOutPath = inOutPaths[0];            }            else                _LLInOutPath = SequenceLLInOutPath.DInDOut;        }        private bool GetAllJobRecipe(ControlJobInfo cj,SequenceInfo seq)        {            for (int i = 0; i < seq.Steps.Count; i++)            {                SequenceStepInfo stepInfo = seq.Steps[i];                foreach (var module in stepInfo.StepModules)                {                    if (ModuleHelper.IsPm(module))                    {                        string attr = $"{module}Recipe";                        if (stepInfo.StepParameter.ContainsKey(attr)                            && !string.IsNullOrWhiteSpace((string)stepInfo.StepParameter[attr]))                        {                            var recipeName = (string)stepInfo.StepParameter[attr];                            var recipeContent =                                    RecipeFileManager.Instance.LoadRecipe($"{module}", recipeName, false, "Process");                            var recipe = Recipe.Load(recipeContent);                            if (recipe.Header.ChuckRecipe != null && recipe.Header.ChuckRecipe != "")                            {                                InUseRecipes.Add($"{module}.ChuckRecipe.{recipe.Header.ChuckRecipe}");                            }                            if (recipe.Header.DechuckRecipe != null && recipe.Header.DechuckRecipe != "")                            {                                InUseRecipes.Add($"{module}.DechuckRecipe.{recipe.Header.DechuckRecipe}");                            }                            InUseRecipes.Add($"{module}.Process.{recipeName}");                            if (cj.PreJobClean != "")                            {                                InUseRecipes.Add($"{module}.Clean.{cj.PreJobClean}");                            }                            if (cj.PostJobClean != "")                            {                                 InUseRecipes.Add($"{module}.Clean.{cj.PostJobClean}");                            }                            if (stepInfo.StepParameter["WTWClean"].ToString() != "")                            {                                InUseRecipes.Add($"{module}.Clean.{stepInfo.StepParameter["WTWClean"]}");                            }                        }                    }                }            }            return true;        }        private bool IsSequenceNeedAlign(SequenceInfo sequence)        {            // check wether need align            foreach (var step in sequence.Steps)            {                foreach(var mod in step.StepModules)                {                    if(ModuleHelper.IsAligner(mod))                        return true;                }            }            return false;        }        #endregion    }}
 |