BrooksSmifPort.cs 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908
  1. using Aitex.Core.Common;
  2. using Aitex.Core.RT.Device.Unit;
  3. using Aitex.Core.RT.Event;
  4. using Aitex.Core.RT.Log;
  5. using Aitex.Core.RT.Routine;
  6. using Aitex.Core.RT.SCCore;
  7. using Aitex.Core.Util;
  8. using Aitex.Sorter.Common;
  9. using Brooks.WinSECS;
  10. using MECF.Framework.Common.Communications;
  11. using MECF.Framework.Common.Equipment;
  12. using MECF.Framework.Common.SubstrateTrackings;
  13. using MECF.Framework.RT.EquipmentLibrary.HardwareUnits.LoadPorts.LoadPortBase;
  14. using MECF.Framework.RT.EquipmentLibrary.HardwareUnits.Robots.RobotBase;
  15. using MECF.Framework.RT.EquipmentLibrary.HardwareUnits.SMIFs.Brooks;
  16. using System;
  17. using System.Collections.Generic;
  18. using System.Linq;
  19. using System.Text;
  20. using System.Threading;
  21. using System.Threading.Tasks;
  22. namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.LoadPorts.SMIF
  23. {
  24. public class BrooksSmifPort : LoadPortBaseDevice, IConnection
  25. {
  26. public WinSECS wshost { get; set; }
  27. public BrooksSMIFHostAgent ha { get; set; }
  28. protected bool _isLoaded;
  29. protected bool _isUnloaded;
  30. public bool IsActionComplete { get; set; }
  31. public override bool IsLoaded => _isLoaded;
  32. public bool IsAutoMode { get; set; }
  33. public bool IsPioInterlockOn { get; set; }
  34. public bool IsPodPresent { get; set; }
  35. public bool IsOpStatusReady { get; set; }
  36. public LastFunctionEnum LastFunctionDone { get; set; }
  37. public PortStateEnum CurrentPortStatus { get; set; }
  38. public bool IsLiftAtOverTravelLimit { get; set; }
  39. public bool IsLiftAtUpLimit { get; set; }
  40. public bool IsLiftAtStagePosition { get; set; }
  41. public WaferSeaterStateEnum CurrentWaferSeaterStatus { get; set; }
  42. public bool IsNormalModeNotServiceMode { get; set; }
  43. public int PortLifterSlotPosition { get; set; }
  44. public bool IsArmRetract { get; set; }
  45. public bool IsAlarm { get; set; }
  46. public bool IsDisableEvenSlot
  47. {
  48. get
  49. {
  50. if (SC.ContainsItem($"CarrierInfo.Carrier{InfoPadCarrierIndex}.DisableEvenSlot"))
  51. return SC.GetValue<bool>($"CarrierInfo.Carrier{InfoPadCarrierIndex}.DisableEvenSlot");
  52. return false;
  53. }
  54. }
  55. public bool IsDisableOddSlot
  56. {
  57. get
  58. {
  59. if (SC.ContainsItem($"CarrierInfo.Carrier{InfoPadCarrierIndex}.DisableOddSlot"))
  60. return SC.GetValue<bool>($"CarrierInfo.Carrier{InfoPadCarrierIndex}.DisableOddSlot");
  61. return false;
  62. }
  63. }
  64. public bool IsConnected { get; set; }
  65. // public override bool IsLoad { get; set; }
  66. private R_TRIG _trigError = new R_TRIG();
  67. private R_TRIG _trigCommunicationError = new R_TRIG();
  68. private R_TRIG _trigRetryConnect = new R_TRIG();
  69. private DeviceTimer _reConnectdTimer = new DeviceTimer();
  70. private PeriodicJob _thread;
  71. protected object _locker = new object();
  72. private bool _enableLog;
  73. private string _errorCode = "";
  74. private DeviceTimer _setStatusTimer = new DeviceTimer();
  75. private int SetStatusTime = 800;
  76. private DateTime _dtStartAction;
  77. private string _scRoot;
  78. public WaferSize DefaultWaferSize = WaferSize.WS8;
  79. public override WaferSize GetCurrentWaferSize()
  80. {
  81. return DefaultWaferSize;
  82. }
  83. public override LoadportCassetteState CassetteState
  84. {
  85. get
  86. {
  87. if (IsPodPresent)
  88. return LoadportCassetteState.Normal;
  89. return LoadportCassetteState.Absent;
  90. }
  91. }
  92. public string Address { get; private set; }
  93. public BrooksSmifPort(string module, string name, string scRoot, RobotBaseDevice robot, bool mapbyLp = true,int slotsCount = 25) : base(module, name, robot,null,slotsCount)
  94. {
  95. Module = module;
  96. Name = name;
  97. _scRoot = scRoot;
  98. string commPort = SC.GetStringValue($"LoadPort.{Name}.PortName");
  99. if (!Enum.TryParse(name, out ModuleName m))
  100. Enum.TryParse(module, out m);
  101. //Instantiate the WinSecs objects for the Host
  102. wshost = new WinSECS();
  103. //Set the PortType for RS232 communication
  104. wshost.PortType = SECS_PORT_TYPE.SECS1_SERIAL;
  105. //Properties that apply to all port types
  106. wshost.AutoDevice = true;
  107. wshost.DefaultDeviceID = 0;
  108. wshost.Secs1.IgnoreSytemBytes = false;
  109. wshost.MultipleOpen = true;
  110. wshost.MonitorEnabled = true;
  111. //Properties that apply to all SECS1 port types, which includes RS232
  112. wshost.Secs1.AcceptDupBlock = false;
  113. wshost.Secs1.Interleave = true;
  114. wshost.Secs1.RetryCount = 10;
  115. wshost.Secs1.SecsHost = true;
  116. wshost.Secs1.T1 = 1;
  117. wshost.Secs1.T2 = 10;
  118. wshost.Secs1.T3 = 30;
  119. wshost.Secs1.T4 = 45;
  120. wshost.Secs1.AutoBaud = false;
  121. wshost.Secs1.PortName = commPort;
  122. wshost.Secs1.BaudRate = 9600;
  123. //Set up the agents that deals with the SECS messages
  124. ha = new BrooksSMIFHostAgent(wshost, this);
  125. wshost.OpenPort(ha);
  126. if (wshost.PortIsOpen)
  127. {
  128. IsConnected = true;
  129. }
  130. ConnectionManager.Instance.Subscribe($"{Name}", this);
  131. IsMapWaferByLoadPort = mapbyLp;
  132. }
  133. public void OnErrorArrived(string alarmcode, string alarmdecri, string alarmtext)
  134. {
  135. if (alarmcode == "5")
  136. {
  137. if (_ErrorDict.ContainsKey(alarmdecri))
  138. EV.PostWarningLog(Name, $"AlarmID:({alarmdecri}){_ErrorDict[alarmdecri]},AlarmText{alarmtext}");
  139. OnError();
  140. }
  141. if (alarmcode == "6")
  142. {
  143. if (_ErrorDict.ContainsKey(alarmdecri))
  144. EV.PostAlarmLog(Name, $"AlarmID:({alarmdecri}){_ErrorDict[alarmdecri]},AlarmText{alarmtext}");
  145. OnError();
  146. }
  147. }
  148. public void OnStausArrived(object[] datas)
  149. {
  150. try
  151. {
  152. string templog = "";
  153. foreach (var data in datas)
  154. templog += data.ToString() + " ";
  155. LOG.Write($"{LPModuleName} received data message:{templog}");
  156. IsPioInterlockOn = datas[0].ToString() == "1";
  157. IsPodPresent = datas[1].ToString() == "1";
  158. if (IsPodPresent)
  159. {
  160. OnCarrierPresent();
  161. OnCarrierPlaced();
  162. }
  163. else
  164. {
  165. OnCarrierNotPresent();
  166. OnCarrierNotPlaced();
  167. }
  168. IsOpStatusReady = datas[2].ToString() == "1";
  169. IsHomed = datas[3].ToString() == "1";
  170. LastFunctionDone = (LastFunctionEnum)Convert.ToInt32(datas[4]);
  171. CurrentPortStatus = (PortStateEnum)Convert.ToInt32(datas[5]);
  172. IsLiftAtOverTravelLimit = datas[6].ToString() == "1";
  173. IsLiftAtUpLimit = datas[7].ToString() == "1";
  174. IsLiftAtStagePosition = datas[8].ToString() == "1";
  175. CurrentWaferSeaterStatus = (WaferSeaterStateEnum)Convert.ToInt32(datas[9]);
  176. IsNormalModeNotServiceMode = datas[10].ToString() == "1";
  177. PortLifterSlotPosition = Convert.ToInt32(datas[11]);
  178. }
  179. catch (Exception ex)
  180. {
  181. LOG.Write(ex);
  182. }
  183. }
  184. internal void OnEventArrived(string eventID)
  185. {
  186. EV.PostInfoLog("LoadPort", $"{LPModuleName} received event,CEID:{eventID}");
  187. if (int.TryParse(eventID, out int index))
  188. {
  189. BrooksSMIFEventEnum eventname = (BrooksSMIFEventEnum)index;
  190. switch (eventname)
  191. {
  192. case BrooksSMIFEventEnum.AutoMode:
  193. IsAutoMode = true;
  194. break;
  195. case BrooksSMIFEventEnum.ManualMode:
  196. IsAutoMode = false;
  197. break;
  198. case BrooksSMIFEventEnum.PodArrived:
  199. IsPodPresent = true;
  200. OnCarrierPresent();
  201. OnCarrierPlaced();
  202. _isLoaded = false;
  203. break;
  204. case BrooksSMIFEventEnum.PodRemoved:
  205. IsPodPresent = false;
  206. OnCarrierNotPresent();
  207. OnCarrierNotPlaced();
  208. break;
  209. case BrooksSMIFEventEnum.ReachStage:
  210. DockState = FoupDockState.Docked;
  211. _isLoaded = true;
  212. DoorState = FoupDoorState.Open;
  213. EV.PostInfoLog("LoadPort", $"{LPModuleName} complete load");
  214. break;
  215. case BrooksSMIFEventEnum.BeginLoad:
  216. EV.PostInfoLog("LoadPort", $"{LPModuleName} start to load");
  217. break;
  218. case BrooksSMIFEventEnum.CompleteLoad:
  219. DockState = FoupDockState.Docked;
  220. _isLoaded = true;
  221. DoorState = FoupDoorState.Open;
  222. EV.PostInfoLog("LoadPort", $"{LPModuleName} complete load");
  223. break;
  224. case BrooksSMIFEventEnum.AbortLoad:
  225. OnError("LoadAborted");
  226. break;
  227. case BrooksSMIFEventEnum.BeginUnload:
  228. EV.PostInfoLog("LoadPort", $"{LPModuleName} start to unload");
  229. break;
  230. case BrooksSMIFEventEnum.CompleteUnload:
  231. DockState = FoupDockState.Undocked;
  232. _isUnloaded = true;
  233. DoorState = FoupDoorState.Close;
  234. _isLoaded = false;
  235. break;
  236. case BrooksSMIFEventEnum.AbortUnload:
  237. OnError("UnloadAborted");
  238. break;
  239. case BrooksSMIFEventEnum.BeginHome:
  240. EV.PostInfoLog("LoadPort", $"{LPModuleName} start to home");
  241. break;
  242. case BrooksSMIFEventEnum.ReachHome:
  243. _isLoaded = false;
  244. _isUnloaded = true;
  245. DoorState = FoupDoorState.Close;
  246. DockState = FoupDockState.Undocked;
  247. IsHomed = true;
  248. break;
  249. case BrooksSMIFEventEnum.AbortHome:
  250. OnError("HomeAborted");
  251. break;
  252. }
  253. }
  254. lock (_locker)
  255. {
  256. SECSTransactionBuilder.BuildS1F5(0).Send(wshost);
  257. }
  258. }
  259. internal void OnTagFileWriteComplete()
  260. {
  261. IsWriteSmartTagComplete = true;
  262. }
  263. public void OnTagFileRead(string strTag)
  264. {
  265. CurrentReadSmartTagFileText = strTag;
  266. IsReadSmartTagFileBack = true;
  267. }
  268. private static Dictionary<string, string> _ErrorDict = new Dictionary<string, string>()
  269. {
  270. {"1","Move to Stage" },
  271. {"2","Return Home" },
  272. {"8","Wafer Map" },
  273. {"32","Port lock or unlock" },
  274. {"34","Move to a specified position" },
  275. {"37","Others" },
  276. {"38","X Move (shuttle failure)" },
  277. };
  278. private static Dictionary<string, string> _RealyMessageDict = new Dictionary<string, string>()
  279. {
  280. {"OK","Comment accepted" },
  281. {"BUSY","Command rejected, LPI is busy" },
  282. {"ALARM","Command rejected, LPI in alarm state" },
  283. {"NO_POD","Command rejected, Pod not on LPI" },
  284. {"NOT_READY","Command rejected, Host interlock not enabled" },
  285. {"INVALID_ARG","Command rejected, at least one invalid parameter" },
  286. {"CANNOT_PERFORM","LPI not in the proper state to perform the Host command" },
  287. {"DENIED","Command rejected for other reason" },
  288. };
  289. private static Dictionary<string, string> _AlarmTimeCodeDict = new Dictionary<string, string>()
  290. {
  291. {"00","No alarm" },
  292. {"41","Alarm occurred during a fetch or open operation" },
  293. {"42","Alarm occurred during a cassette placement on the process tool" },
  294. {"43","Alarm occurred during a returning of the minienvironment to Home" },
  295. {"44","Alarm occurred during a retrieval of the cassette from the Tool" },
  296. {"45","Alarm occurred during a placement of the cassette on the Pod door" },
  297. {"46","Non-recoverable fatal error" }
  298. };
  299. private static Dictionary<string, string> _ErrorCodeDict = new Dictionary<string, string>()
  300. {
  301. {"00","No error" },
  302. {"01","Position following error" },
  303. {"02","LPI not Home" },
  304. {"03","LPI busy" },
  305. {"04","Pod removed/missing elevator door" },
  306. {"05","Aborted by user" },
  307. {"07","Protrusion sensor failure" },
  308. {"08","Slot sensor failure" },
  309. {"09","Wafer presence sensor failure" },
  310. {"10","Flash sensor failure" },
  311. {"11","Elevator over-travel limit trip" },
  312. {"13","Excessive wafer protrusion" },
  313. {"14","System internal time-out" },
  314. {"15","Servo command error" },
  315. {"16","Pod door open time-out" },
  316. {"17","Pod door close time-out" },
  317. {"18","Pod hold-down open time-out" },
  318. {"19","Pod hold-down close time-out" },
  319. {"20","Wafer seater failed to move toward wafer" },
  320. {"21","Wafer seater failed to return to Home" },
  321. {"22","Elevator failed to reach target position" },
  322. {"24","System error" },
  323. {"27","Loss of configuration data" },
  324. {"28","Cassette not present" },
  325. {"29","Loss of air flow" },
  326. {"31","Gripper open time out" },
  327. {"32","Gripper close time out" },
  328. {"33","Interprocessor communication error" },
  329. {"34","Gripper overtravel" },
  330. {"35","Cassette found during unload" },
  331. };
  332. internal void OnAlarmArrived(string alarmData)
  333. {
  334. EV.PostAlarmLog(Name, $"alarmdata:{alarmData}");
  335. if (alarmData.Length != 4)
  336. return;
  337. string alarmTimeCode = alarmData.Substring(0, 2);
  338. string alarmInfoCode = alarmData.Substring(2, 2);
  339. AlarmOccurTime = alarmTimeCode + "=" + _AlarmTimeCodeDict[alarmTimeCode];
  340. AlarmInfo = alarmInfoCode + "=" + _ErrorCodeDict[alarmInfoCode];
  341. EV.PostAlarmLog(Module, $"{Module} {AlarmOccurTime}, for {AlarmInfo}");
  342. OnError();
  343. IsAlarm = true;
  344. }
  345. public override void Reset()
  346. {
  347. _trigError.RST = true;
  348. _trigCommunicationError.RST = true;
  349. _trigRetryConnect.RST = true;
  350. }
  351. protected override bool fStartReset(object[] param)
  352. {
  353. lock (_locker)
  354. {
  355. SECSTransactionBuilder.BuildS2F41((int)BrooksSMIFRCMDEnum.Reset).Send(wshost);
  356. SECSTransactionBuilder.BuildS1F5(0).Send(wshost);
  357. }
  358. return true;
  359. }
  360. protected override bool fMonitorReset(object[] param)
  361. {
  362. IsBusy = false;
  363. return true;
  364. }
  365. #region Command Functions
  366. protected override bool fStartInit(object[] param)
  367. {
  368. IsHomed = false;
  369. lock (_locker)
  370. {
  371. SECSTransactionBuilder.BuildS1F5(0).Send(wshost);
  372. SECSTransactionBuilder.BuildS2F41((int)BrooksSMIFRCMDEnum.GoHome).Send(wshost);
  373. }
  374. _dtStartAction = DateTime.Now;
  375. return true;
  376. }
  377. protected override bool fMonitorInit(object[] param)
  378. {
  379. IsBusy = false;
  380. if (DateTime.Now - _dtStartAction > TimeSpan.FromSeconds(TimelimitHome))
  381. {
  382. OnError("InitTimeout");
  383. return true;
  384. }
  385. return IsHomed;
  386. }
  387. protected override bool fStartLoad(object[] objs)
  388. {
  389. ResetRoutine();
  390. return true;
  391. }
  392. protected override bool fMonitorLoad(object[] param)
  393. {
  394. IsBusy = false;
  395. LoadCassette((int)LpStepEnum.Step1, TimelimitAction, OnError);
  396. if (ExecuteResult.Item1)
  397. {
  398. return false;
  399. }
  400. if (IsMapWaferByLoadPort)
  401. {
  402. QueryMap((int)LpStepEnum.Step2, TimelimitAction, OnError);
  403. if (ExecuteResult.Item1)
  404. {
  405. return false;
  406. }
  407. }
  408. IsBusy = false;
  409. return true;
  410. }
  411. protected override bool fStartExecute(object[] param)
  412. {
  413. try
  414. {
  415. IsActionComplete = false;
  416. switch (param[0].ToString())
  417. {
  418. case "Unclamp":
  419. lock (_locker)
  420. {
  421. SECSTransactionBuilder.BuildS2F41((int)BrooksSMIFRCMDEnum.HostToUnlockPort).Send(wshost);
  422. }
  423. break;
  424. case "Clamp":
  425. lock (_locker)
  426. {
  427. SECSTransactionBuilder.BuildS2F41((int)BrooksSMIFRCMDEnum.HostToLockPort).Send(wshost);
  428. }
  429. break;
  430. case "MapWafer":
  431. lock (_locker)
  432. {
  433. if (!IsMapWaferByLoadPort)
  434. {
  435. if (MapRobot != null)
  436. return MapRobot.WaferMapping(LPModuleName, out _);
  437. return false;
  438. }
  439. }
  440. break;
  441. }
  442. _dtStartAction = DateTime.Now;
  443. return true;
  444. }
  445. catch (Exception ex)
  446. {
  447. LOG.Write(ex);
  448. EV.PostAlarmLog(Name, $"Parameter invalid");
  449. return false;
  450. }
  451. }
  452. protected override bool fMonitorExecuting(object[] param)
  453. {
  454. IsBusy = false;
  455. if (DateTime.Now - _dtStartAction > TimeSpan.FromSeconds(TimelimitHome))
  456. {
  457. OnError("InitTimeout");
  458. return true;
  459. }
  460. switch (CurrentParamter[0].ToString())
  461. {
  462. case "Unclamp":
  463. return CurrentPortStatus == PortStateEnum.Unlock;
  464. case "Clamp":
  465. return CurrentPortStatus == PortStateEnum.Lock;
  466. case "MapWafer":
  467. break;
  468. default:
  469. return true;
  470. }
  471. return false;
  472. }
  473. public override bool Stop(out string reason)
  474. {
  475. lock (_locker)
  476. {
  477. SECSTransactionBuilder.BuildS2F41((int)BrooksSMIFRCMDEnum.EmergencyStop).Send(wshost);
  478. }
  479. return base.Stop(out reason);
  480. }
  481. public bool QueryMapStatus(out string reason)
  482. {
  483. //IsBusy = true;
  484. reason = string.Empty;
  485. lock (_locker)
  486. {
  487. SECSTransactionBuilder.BuildS1F5(2).Send(wshost);
  488. }
  489. if (!_setStatusTimer.IsIdle())
  490. _setStatusTimer.Stop();
  491. _setStatusTimer.Start(0);
  492. return true;
  493. }
  494. public bool QueryPortStatus(out string reason)
  495. {
  496. reason = string.Empty;
  497. lock (_locker)
  498. {
  499. SECSTransactionBuilder.BuildS1F5(0).Send(wshost);
  500. }
  501. //IsIdle = false;
  502. if (!_setStatusTimer.IsIdle())
  503. _setStatusTimer.Stop();
  504. _setStatusTimer.Start(0);
  505. return true;
  506. }
  507. protected override bool fStartUnload(object[] param)
  508. {
  509. lock (_locker)
  510. {
  511. _isUnloaded = false;
  512. //SECSTransactionBuilder.BuildS2F41((int)BrooksSMIFRCMDEnum.EnableUnload).Send(wshost);
  513. //Thread.Sleep(500);
  514. SECSTransactionBuilder.BuildS2F41((int)BrooksSMIFRCMDEnum.GoHome).Send(wshost);
  515. }
  516. _isUnloaded = false;
  517. _dtStartAction = DateTime.Now;
  518. return true;
  519. }
  520. protected override bool fMonitorUnload(object[] param)
  521. {
  522. IsBusy = false;
  523. if (DateTime.Now - _dtStartAction > TimeSpan.FromSeconds(TimelimitAction))
  524. {
  525. OnError("UnloadTimeout");
  526. EV.Notify(AlarmLoadPortUnloadTimeOut);
  527. return true;
  528. }
  529. if (_isUnloaded)
  530. {
  531. OnUnloaded();
  532. return true;
  533. }
  534. return false;
  535. }
  536. public void OnCarrierNotPlaced()
  537. {
  538. _isPlaced = false;
  539. ConfirmRemoveCarrier();
  540. }
  541. public void OnCarrierNotPresent()
  542. {
  543. _isPresent = false;
  544. //ConfirmRemoveCarrier();
  545. }
  546. public void OnCarrierPlaced()
  547. {
  548. _isPlaced = true;
  549. ConfirmAddCarrier();
  550. }
  551. public void OnCarrierPresent()
  552. {
  553. _isPresent = true;
  554. //ConfirmAddCarrier();
  555. }
  556. public override void OnSlotMapRead(string slotMap)
  557. {
  558. MapError = false;
  559. CurrentSlotMapResult = slotMap;
  560. for (int i = 0; i < slotMap.Length; i++)
  561. {
  562. // No wafer: "0", Wafer: "1", Crossed:"2", Undefined: "?", Overlapping wafers: "W"
  563. WaferInfo wafer = null;
  564. if (i >= SlotsCount)
  565. continue;
  566. if (IsMapWaferByLoadPort)
  567. {
  568. CurrentSlotMapResult = slotMap.Replace("0", "?").Replace("1", "0").Replace("2", "1");
  569. switch (slotMap[i])
  570. {
  571. case '2':
  572. WaferManager.Instance.DeleteWafer(LPModuleName, i);
  573. CarrierManager.Instance.UnregisterCarrierWafer(Name, i);
  574. break;
  575. case '1':
  576. wafer = WaferManager.Instance.CreateWafer(LPModuleName, i, WaferStatus.Normal, GetCurrentWaferSize());
  577. CarrierManager.Instance.RegisterCarrierWafer(Name, i, wafer);
  578. break;
  579. case '4':
  580. wafer = WaferManager.Instance.CreateWafer(LPModuleName, i, WaferStatus.Crossed, GetCurrentWaferSize());
  581. WaferManager.Instance.CheckWaferSize(LPModuleName, i, GetCurrentWaferSize());
  582. CarrierManager.Instance.RegisterCarrierWafer(Name, i, wafer);
  583. OnError($"MappingError:Slot:{i + 1} crossedwafer");
  584. //NotifyWaferError(Name, i, WaferStatus.Crossed);
  585. break;
  586. default:
  587. wafer = WaferManager.Instance.CreateWafer(LPModuleName, i, WaferStatus.Unknown, GetCurrentWaferSize());
  588. CarrierManager.Instance.RegisterCarrierWafer(Name, i, wafer);
  589. //NotifyWaferError(Name, i, WaferStatus.Unknown);
  590. OnError($"MappingError:Slot:{i + 1} unknowwafer");
  591. break;
  592. }
  593. }
  594. else
  595. {
  596. switch (slotMap[i])
  597. {
  598. case '0':
  599. WaferManager.Instance.DeleteWafer(LPModuleName, i);
  600. CarrierManager.Instance.UnregisterCarrierWafer(Name, i);
  601. break;
  602. case '1':
  603. if ((IsDisableEvenSlot && i % 2 == 1) || (IsDisableOddSlot && i % 2 == 0))
  604. {
  605. OnMapError($"Slot{i + 1}WaferOn");
  606. wafer = WaferManager.Instance.CreateWafer(LPModuleName, i, WaferStatus.Unknown, GetCurrentWaferSize());
  607. }
  608. else
  609. wafer = WaferManager.Instance.CreateWafer(LPModuleName, i, WaferStatus.Normal, GetCurrentWaferSize());
  610. WaferManager.Instance.CheckWaferSize(LPModuleName, i, GetCurrentWaferSize());
  611. CarrierManager.Instance.RegisterCarrierWafer(Name, i, wafer);
  612. break;
  613. case '?':
  614. if ((IsDisableEvenSlot && i % 2 == 1) || (IsDisableOddSlot && i % 2 == 0))
  615. {
  616. OnMapError($"Slot{i + 1}WaferOn");
  617. }
  618. wafer = WaferManager.Instance.CreateWafer(LPModuleName, i, WaferStatus.Crossed, GetCurrentWaferSize());
  619. WaferManager.Instance.CheckWaferSize(LPModuleName, i, GetCurrentWaferSize());
  620. CarrierManager.Instance.RegisterCarrierWafer(Name, i, wafer);
  621. OnMapError($"MappingError:Slot:{i + 1} crossedwafer");
  622. //NotifyWaferError(Name, i, WaferStatus.Crossed);
  623. break;
  624. case 'W':
  625. if ((IsDisableEvenSlot && i % 2 == 1) || (IsDisableOddSlot && i % 2 == 0))
  626. {
  627. OnMapError($"Slot{i + 1}WaferOn");
  628. }
  629. wafer = WaferManager.Instance.CreateWafer(LPModuleName, i, WaferStatus.Double, GetCurrentWaferSize());
  630. WaferManager.Instance.CheckWaferSize(LPModuleName, i, GetCurrentWaferSize());
  631. CarrierManager.Instance.RegisterCarrierWafer(Name, i, wafer);
  632. OnMapError($"MappingError:Slot:{i + 1} doublewafer");
  633. //NotifyWaferError(Name, i, WaferStatus.Double);
  634. break;
  635. default:
  636. if ((IsDisableEvenSlot && i % 2 == 1) || (IsDisableOddSlot && i % 2 == 0))
  637. {
  638. OnMapError($"Slot{i + 1}WaferOn");
  639. }
  640. wafer = WaferManager.Instance.CreateWafer(LPModuleName, i, WaferStatus.Unknown, GetCurrentWaferSize());
  641. WaferManager.Instance.CheckWaferSize(LPModuleName, i, GetCurrentWaferSize());
  642. CarrierManager.Instance.RegisterCarrierWafer(Name, i, wafer);
  643. OnMapError($"MappingError:Slot:{i + 1} unknowwafer");
  644. //NotifyWaferError(Name, i, WaferStatus.Unknown);
  645. break;
  646. }
  647. }
  648. }
  649. if (CurrentSlotMapResult.Contains("2"))
  650. {
  651. MapError = true;
  652. EV.Notify(AlarmLoadPortMapCrossedWafer);
  653. EV.Notify(AlarmLoadPortMappingError);
  654. }
  655. if (CurrentSlotMapResult.Contains("4"))
  656. {
  657. MapError = true;
  658. EV.Notify(AlarmLoadPortMapCrossedWafer);
  659. EV.Notify(AlarmLoadPortMappingError);
  660. }
  661. if (CurrentSlotMapResult.Contains("W"))
  662. {
  663. MapError = true;
  664. EV.Notify(AlarmLoadPortMapDoubleWafer);
  665. EV.Notify(AlarmLoadPortMappingError);
  666. }
  667. if (CurrentSlotMapResult.Contains("?"))
  668. {
  669. MapError = true;
  670. EV.Notify(AlarmLoadPortMapUnknownWafer);
  671. EV.Notify(AlarmLoadPortMappingError);
  672. }
  673. if (MapError)
  674. {
  675. Unload(out _);
  676. }
  677. SerializableDictionary<string, object> dvid = new SerializableDictionary<string, object>();
  678. dvid["SlotMap"] = CurrentSlotMapResult;
  679. dvid["PortID"] = PortID;
  680. dvid["PORT_CTGRY"] = SpecPortName;
  681. dvid["CarrierType"] = SpecCarrierType;
  682. dvid["CarrierIndex"] = InfoPadCarrierIndex;
  683. dvid["InfoPadSensorIndex"] = InfoPadSensorIndex;
  684. dvid["CarrierID"] = CarrierId;
  685. EV.Notify(EventSlotMapAvailable, dvid);
  686. EV.Notify(EventMapComplete, dvid);
  687. if (LPCallBack != null)
  688. LPCallBack.MappingComplete(_carrierId, CurrentSlotMapResult);
  689. _isMapped = true;
  690. }
  691. private void OnMapError(string errText)
  692. {
  693. EV.Notify(AlarmLoadPortError);
  694. EV.PostAlarmLog("LoadPort", $"{LPModuleName} occurried error:{errText} with carrier:{CarrierId ?? ""}.");
  695. }
  696. #endregion
  697. #region Properties
  698. public string AlarmOccurTime { get; private set; }
  699. public string AlarmInfo { get; private set; }
  700. #endregion
  701. public override void Terminate()
  702. {
  703. }
  704. public override void Monitor()
  705. {
  706. if (!IsConnected && ha != null && (_reConnectdTimer.IsIdle() || _reConnectdTimer.GetElapseTime() > 10000))
  707. {
  708. wshost.ClosePort();
  709. wshost.OpenPort(ha);
  710. _reConnectdTimer.Start(0);
  711. }
  712. if (IsConnected)
  713. {
  714. _reConnectdTimer.Stop();
  715. }
  716. if (!IsPlacement)
  717. {
  718. _isLoaded = false;
  719. }
  720. }
  721. public override bool IsEnableMapWafer(out string reason)
  722. {
  723. reason = "";
  724. if (!_isLoaded)
  725. {
  726. reason = "Not loaded";
  727. return false;
  728. }
  729. if (!IsReady())
  730. {
  731. reason = "Not Ready";
  732. return false;
  733. }
  734. if (_isPresent && _isPlaced && CassetteState == LoadportCassetteState.Normal)
  735. return true;
  736. reason = "No cassette";
  737. return false;
  738. }
  739. public override bool IsEnableTransferWafer(out string reason)
  740. {
  741. reason = "";
  742. if (!IsReady())
  743. {
  744. reason = "Not ready";
  745. return false;
  746. }
  747. if (!_isLoaded)
  748. {
  749. reason = "Not loaded";
  750. return false;
  751. }
  752. if (!_isMapped)
  753. {
  754. reason = "Not Mapped";
  755. return false;
  756. }
  757. if (CurrentSlotMapResult.Contains("2"))
  758. {
  759. reason = "Cross wafer";
  760. return false;
  761. }
  762. if (CurrentSlotMapResult.Contains("3"))
  763. {
  764. reason = "Double wafer";
  765. return false;
  766. }
  767. if (CurrentSlotMapResult.Contains("4"))
  768. {
  769. reason = "Double wafer";
  770. return false;
  771. }
  772. if (_isPresent && _isPlaced && CassetteState == LoadportCassetteState.Normal)
  773. return true;
  774. reason = "No cassette";
  775. return false;
  776. }
  777. public override bool IsEnableUnload(out string reason)
  778. {
  779. reason = "";
  780. return true;
  781. }
  782. public override bool IsEnableLoad(out string reason)
  783. {
  784. reason = "";
  785. return true;
  786. }
  787. public override bool Connect()
  788. {
  789. return true;
  790. }
  791. public bool Disconnect()
  792. {
  793. return true;
  794. }
  795. protected override bool fStartWrite(object[] param)
  796. {
  797. return true;
  798. }
  799. protected override bool fStartRead(object[] param)
  800. {
  801. return true;
  802. }
  803. public override bool ReadCarrierID()
  804. {
  805. return ReadCarrierIDByIndex(0, 16);
  806. }
  807. public override bool ReadCarrierIDByIndex(int offset = 0, int length = 16, int index = 0)
  808. {
  809. if (CIDReaders != null && CIDReaders.Length > 0 && CIDReaders[0] != null)
  810. {
  811. return base.ReadCarrierIDByIndex(offset, length, index);
  812. }
  813. ReadSmifSmartTag();
  814. return true;
  815. }
  816. public virtual void ReadSmifSmartTag()
  817. {
  818. SECSTransaction secsTransaction = new SECSTransaction(100, 121);
  819. secsTransaction.Primary.Root.Name = "S100F121";
  820. secsTransaction.Primary.Root.AddNew("L2a", "");
  821. secsTransaction.Primary.Root.Item("L2a").Format = SECS_FORMAT.U4;
  822. secsTransaction.Primary.Root.Item("L2a").Value = 7;
  823. //secsTransaction.Primary.Root.Item("L2a").Format = SECS_FORMAT.LIST;
  824. //secsTransaction.Primary.Root.Item("L2a").AddNew("Param1", "");
  825. //secsTransaction.Primary.Root.Item("L2a").Item("Param1").Format = SECS_FORMAT.U4;
  826. //secsTransaction.Primary.Root.Item("L2a").Item("Param1").Value = 7;
  827. secsTransaction.ReplyExpected = true;
  828. secsTransaction.Send(wshost);
  829. }
  830. public override bool GetCarrierID(int offset, int length, string tagid, out string carrierId)
  831. {
  832. carrierId = "";
  833. ReadSmifSmartTagFile(tagid);
  834. int waitCount = 0;
  835. while (!IsReadSmartTagFileBack)
  836. {
  837. Thread.Sleep(100);
  838. waitCount++;
  839. if (waitCount > 200)
  840. {
  841. return false;
  842. }
  843. }
  844. carrierId = CurrentReadSmartTagFileText;
  845. return true;
  846. }
  847. public bool IsReadSmartTagFileBack;
  848. public bool IsWriteSmartTagComplete;
  849. public string CurrentReadSmartTagFileText;
  850. public virtual void ReadSmifSmartTagFile(string file)
  851. {
  852. SECSTransaction secsTransaction = new SECSTransaction(100, 109);
  853. secsTransaction.Primary.Root.Name = "S100F109";
  854. secsTransaction.Primary.Root.AddNew("L2a", "");
  855. secsTransaction.Primary.Root.Item("L2a").Format = SECS_FORMAT.LIST;
  856. secsTransaction.Primary.Root.Item("L2a").AddNew("FileIndex");
  857. secsTransaction.Primary.Root.Item("L2a").Item("FileIndex").Format = SECS_FORMAT.U4;
  858. secsTransaction.Primary.Root.Item("L2a").Item("FileIndex").Value = 0;
  859. secsTransaction.Primary.Root.Item("L2a").AddNew("FileName");
  860. secsTransaction.Primary.Root.Item("L2a").Item("FileName").Format = SECS_FORMAT.ASCII;
  861. secsTransaction.Primary.Root.Item("L2a").Item("FileName").Value = file;
  862. secsTransaction.ReplyExpected = true;
  863. IsReadSmartTagFileBack = false;
  864. secsTransaction.Send(wshost);
  865. }
  866. public override bool WriteCarrierID(string cid, int offset, int length, string tagid, out string reason)
  867. {
  868. reason = "";
  869. WriteTagfile(tagid, cid);
  870. int waitCount = 0;
  871. while (true)
  872. {
  873. if (IsWriteSmartTagComplete)
  874. return true;
  875. Thread.Sleep(100);
  876. waitCount++;
  877. if (waitCount > 150)
  878. break;
  879. }
  880. reason = "TimeOut";
  881. return false;
  882. }
  883. public void WriteTagfile(string filename, string tag)
  884. {
  885. SECSTransaction secsTransaction = new SECSTransaction(100, 107);
  886. secsTransaction.Primary.Root.Name = "S100F107";
  887. secsTransaction.Primary.Root.AddNew("L2a", "");
  888. secsTransaction.Primary.Root.Item("L2a").Format = SECS_FORMAT.LIST;
  889. secsTransaction.Primary.Root.Item("L2a").AddNew("FileIndex");
  890. secsTransaction.Primary.Root.Item("L2a").Item("FileIndex").Format = SECS_FORMAT.U4;
  891. secsTransaction.Primary.Root.Item("L2a").Item("FileIndex").Value = 0;
  892. secsTransaction.Primary.Root.Item("L2a").AddNew("FileIndex1");
  893. secsTransaction.Primary.Root.Item("L2a").Item("FileIndex1").Format = SECS_FORMAT.U1;
  894. secsTransaction.Primary.Root.Item("L2a").Item("FileIndex1").Value = 1;
  895. secsTransaction.Primary.Root.Item("L2a").AddNew("FileName");
  896. secsTransaction.Primary.Root.Item("L2a").Item("FileName").Format = SECS_FORMAT.ASCII;
  897. secsTransaction.Primary.Root.Item("L2a").Item("FileName").Value = filename;
  898. secsTransaction.Primary.Root.Item("L2a").AddNew("Parameter1");
  899. secsTransaction.Primary.Root.Item("L2a").Item("Parameter1").Format = SECS_FORMAT.ASCII;
  900. secsTransaction.Primary.Root.Item("L2a").Item("Parameter1").Value = "";
  901. secsTransaction.Primary.Root.Item("L2a").AddNew("Tagcontent");
  902. secsTransaction.Primary.Root.Item("L2a").Item("Tagcontent").Format = SECS_FORMAT.ASCII;
  903. secsTransaction.Primary.Root.Item("L2a").Item("Tagcontent").Value = tag;
  904. secsTransaction.ReplyExpected = true;
  905. IsWriteSmartTagComplete = false;
  906. secsTransaction.Send(wshost);
  907. }
  908. public void LoadCassette(int id, int time, Action<string> error)
  909. {
  910. var ret = ExecuteAndWait(id, () =>
  911. {
  912. EV.PostInfoLog("System", $"{MapRobot.RobotModuleName} start loading");
  913. var reason = string.Empty;
  914. lock (_locker)
  915. {
  916. SECSTransactionBuilder.BuildS2F41((int)BrooksSMIFRCMDEnum.EnableLoad).Send(wshost);
  917. Thread.Sleep(500);
  918. SECSTransactionBuilder.BuildS2F41((int)BrooksSMIFRCMDEnum.GotoStagePosition).Send(wshost);
  919. SECSTransactionBuilder.BuildS1F5(0).Send(wshost);
  920. }
  921. _isLoaded = false;
  922. _isMapped = false;
  923. return true;
  924. }, () =>
  925. {
  926. if (_isLoaded)
  927. return Result.DONE;
  928. return Result.RUN;
  929. }, time * 1000);
  930. if (ret.Item1)
  931. {
  932. if (ret.Item2 == Result.FAIL)
  933. {
  934. error("load failed");
  935. EV.Notify(AlarmLoadPortLoadTimeOut);
  936. }
  937. if (ret.Item2 == Result.TIMEOUT) //timeout
  938. {
  939. error("load timeout");
  940. EV.Notify(AlarmLoadPortLoadTimeOut);
  941. }
  942. }
  943. }
  944. protected void QueryMap(int id, int time, Action<string> error)
  945. {
  946. var ret = ExecuteAndWait(id, () =>
  947. {
  948. EV.PostInfoLog("System", $"{MapRobot.RobotModuleName} start to query map");
  949. var reason = string.Empty;
  950. _isMapped = false;
  951. lock (_locker)
  952. {
  953. SECSTransactionBuilder.BuildS1F5(2).Send(wshost);
  954. }
  955. return true;
  956. }, () =>
  957. {
  958. if (_isMapped)
  959. return Result.DONE;
  960. return Result.RUN;
  961. }, time * 1000);
  962. if (ret.Item1)
  963. {
  964. if (ret.Item2 == Result.FAIL)
  965. error("map failed");
  966. if (ret.Item2 == Result.TIMEOUT) //timeout
  967. {
  968. error("map timeout");
  969. }
  970. }
  971. }
  972. protected void SetDoValue(int id, IoTrigger dotrig, bool bValue)
  973. {
  974. var ret = Execute(id, () =>
  975. {
  976. EV.PostInfoLog("LoadPort", $"{LPModuleName} start to set {dotrig.Name} start to {bValue}");
  977. dotrig.SetTrigger(bValue, out _);
  978. return true;
  979. });
  980. }
  981. public void WaitDiValue(int id, int time, IoSensor disensor, bool bvalue, Action<string> error)
  982. {
  983. var ret = ExecuteAndWait(id, () =>
  984. {
  985. EV.PostInfoLog("System", $"Wait {disensor.Name} to be {bvalue}");
  986. return true;
  987. }, () =>
  988. {
  989. if (disensor.Value == bvalue)
  990. return Result.DONE;
  991. return Result.RUN;
  992. }, time * 1000);
  993. if (ret.Item1)
  994. {
  995. if (ret.Item2 == Result.FAIL)
  996. {
  997. error($"Wait {disensor.Name} to be {bvalue} failed");
  998. }
  999. if (ret.Item2 == Result.TIMEOUT) //timeout
  1000. {
  1001. error($"Wait {disensor.Name} to be {bvalue} timeout");
  1002. }
  1003. }
  1004. }
  1005. public enum LpStepEnum
  1006. {
  1007. Step1,
  1008. Step2,
  1009. Step3,
  1010. Step4,
  1011. Step5,
  1012. Step6,
  1013. Step7,
  1014. Step8,
  1015. Step9,
  1016. Step10,
  1017. Step11,
  1018. Step12,
  1019. }
  1020. protected DeviceTimer counter = new DeviceTimer();
  1021. protected DeviceTimer delayTimer = new DeviceTimer();
  1022. private enum STATE
  1023. {
  1024. IDLE,
  1025. WAIT,
  1026. }
  1027. public int TokenId
  1028. {
  1029. get { return _id; }
  1030. }
  1031. private int _id; //step index
  1032. private int _currentTokenId = -1;
  1033. /// <summary>
  1034. /// already done steps
  1035. /// </summary>
  1036. private Stack<int> _steps = new Stack<int>();
  1037. private STATE state; //step state //idel,wait,
  1038. //loop control
  1039. private int loop = 0;
  1040. private int loopCount = 0;
  1041. private int loopID = 0;
  1042. private DeviceTimer timer = new DeviceTimer();
  1043. public int LoopCounter { get { return loop; } }
  1044. public int LoopTotalTime { get { return loopCount; } }
  1045. // public int Timeout { get { return (int)(timer.GetTotalTime() / 1000); } }
  1046. //状态持续时间,单位为秒
  1047. public int Elapsed { get { return (int)(timer.GetElapseTime() / 1000); } }
  1048. protected RoutineResult RoutineToken = new RoutineResult() { Result = RoutineState.Running };
  1049. protected Tuple<bool, Result> ExecuteResult;
  1050. public void ResetRoutine()
  1051. {
  1052. _id = 0;
  1053. _steps.Clear();
  1054. loop = 0;
  1055. loopCount = 0;
  1056. state = STATE.IDLE;
  1057. counter.Start(60 * 60 * 100); //默认1小时
  1058. RoutineToken.Result = RoutineState.Running;
  1059. _currentTokenId = -1;
  1060. ExecuteResult = Tuple.Create(false, Result.DONE);
  1061. }
  1062. protected void PerformRoutineStep(int id, Func<RoutineState> execution, RoutineResult result)
  1063. {
  1064. if (!Acitve(id))
  1065. return;
  1066. result.Result = execution();
  1067. }
  1068. #region interface
  1069. public void StopLoop()
  1070. {
  1071. loop = loopCount;
  1072. }
  1073. public Tuple<bool, Result> Loop<T>(T id, Func<bool> func, int count)
  1074. {
  1075. int idx = Convert.ToInt32(id);
  1076. bool bActive = Acitve(idx);
  1077. if (bActive)
  1078. {
  1079. if (!func())
  1080. {
  1081. return Tuple.Create(bActive, Result.FAIL); //执行错误
  1082. }
  1083. loopID = idx;
  1084. loopCount = count;
  1085. next();
  1086. return Tuple.Create(true, Result.RUN);
  1087. }
  1088. return Tuple.Create(false, Result.RUN);
  1089. }
  1090. public Tuple<bool, Result> EndLoop<T>(T id, Func<bool> func)
  1091. {
  1092. int idx = Convert.ToInt32(id);
  1093. bool bActive = Acitve(idx);
  1094. if (bActive)
  1095. {
  1096. if (++loop >= loopCount) //Loop 结束
  1097. {
  1098. if (!func())
  1099. {
  1100. return Tuple.Create(bActive, Result.FAIL); //执行错误
  1101. }
  1102. loop = 0;
  1103. loopCount = 0; // Loop 结束时,当前loop和loop总数都清零
  1104. next();
  1105. return Tuple.Create(true, Result.RUN);
  1106. }
  1107. //继续下一LOOP
  1108. next(loopID);
  1109. return Tuple.Create(true, Result.RUN);
  1110. }
  1111. return Tuple.Create(false, Result.RUN);
  1112. }
  1113. public Tuple<bool, Result> ExecuteAndWait<T>(T id, IRoutine routine)
  1114. {
  1115. int idx = Convert.ToInt32(id);
  1116. bool bActive = Acitve(idx);
  1117. if (bActive)
  1118. {
  1119. if (state == STATE.IDLE)
  1120. {
  1121. Result startRet = routine.Start();
  1122. if (startRet == Result.FAIL)
  1123. {
  1124. return Tuple.Create(true, Result.FAIL); //执行错误
  1125. }
  1126. else if (startRet == Result.DONE)
  1127. {
  1128. next();
  1129. return Tuple.Create(true, Result.DONE);
  1130. }
  1131. state = STATE.WAIT;
  1132. }
  1133. Result ret = routine.Monitor();
  1134. if (ret == Result.DONE)
  1135. {
  1136. next();
  1137. return Tuple.Create(true, Result.DONE);
  1138. }
  1139. else if (ret == Result.FAIL || ret == Result.TIMEOUT)
  1140. {
  1141. return Tuple.Create(true, Result.FAIL);
  1142. }
  1143. else
  1144. {
  1145. return Tuple.Create(true, Result.RUN);
  1146. }
  1147. }
  1148. return Tuple.Create(false, Result.RUN);
  1149. }
  1150. public Tuple<bool, Result> ExecuteAndWait<T>(T id, List<IRoutine> routines)
  1151. {
  1152. int idx = Convert.ToInt32(id);
  1153. bool bActive = Acitve(idx);
  1154. if (bActive)
  1155. {
  1156. if (state == STATE.IDLE)
  1157. {
  1158. foreach (var item in routines)
  1159. {
  1160. if (item.Start() == Result.FAIL)
  1161. return Tuple.Create(true, Result.FAIL);
  1162. }
  1163. state = STATE.WAIT;
  1164. }
  1165. //wait all sub failed or completedboo
  1166. bool bFail = false;
  1167. bool bDone = true;
  1168. foreach (var item in routines)
  1169. {
  1170. Result ret = item.Monitor();
  1171. bDone &= (ret == Result.FAIL || ret == Result.DONE);
  1172. bFail |= ret == Result.FAIL;
  1173. }
  1174. if (bDone)
  1175. {
  1176. next();
  1177. if (bFail)
  1178. return Tuple.Create(true, Result.FAIL);
  1179. return Tuple.Create(true, Result.DONE);
  1180. }
  1181. return Tuple.Create(true, Result.RUN);
  1182. }
  1183. return Tuple.Create(false, Result.RUN);
  1184. }
  1185. public Tuple<bool, Result> Check<T>(T id, Func<bool> func) //顺序执行
  1186. {
  1187. return Check(Check(Convert.ToInt32(id), func));
  1188. }
  1189. public Tuple<bool, Result> Execute<T>(T id, Func<bool> func) //顺序执行
  1190. {
  1191. return Check(execute(Convert.ToInt32(id), func));
  1192. }
  1193. public Tuple<bool, Result> Wait<T>(T id, Func<bool> func, double timeout = int.MaxValue) //Wait condition
  1194. {
  1195. return Check(wait(Convert.ToInt32(id), func, timeout));
  1196. }
  1197. public Tuple<bool, Result> Wait<T>(T id, Func<bool?> func, double timeout = int.MaxValue) //Wait condition
  1198. {
  1199. return Check(wait(Convert.ToInt32(id), func, timeout));
  1200. }
  1201. public Tuple<bool, Result> ExecuteAndWait<T>(T id, Func<bool> execute, Func<Result?> check, double timeout = int.MaxValue)
  1202. {
  1203. int idx = Convert.ToInt32(id);
  1204. bool bActive = Acitve(idx);
  1205. Result? bExecute = Result.RUN;
  1206. if (bActive)
  1207. {
  1208. //if (idx != _currentTokenId && ExecuteResult.Item1) return ExecuteResult;
  1209. if (state == STATE.IDLE)
  1210. {
  1211. if (!execute())
  1212. {
  1213. ExecuteResult = Tuple.Create(bActive, Result.FAIL);
  1214. return Tuple.Create(bActive, Result.FAIL); //执行错误
  1215. }
  1216. timer.Start(timeout);
  1217. state = STATE.WAIT;
  1218. _currentTokenId = idx;
  1219. }
  1220. bExecute = check();
  1221. if (bExecute == null)
  1222. {
  1223. ExecuteResult = Tuple.Create(bActive, Result.FAIL);
  1224. return Tuple.Create(bActive, Result.FAIL); //Termianate
  1225. }
  1226. else
  1227. {
  1228. if (bExecute == Result.DONE) //检查Success, next
  1229. {
  1230. next();
  1231. ExecuteResult = Tuple.Create(true, Result.RUN);
  1232. return Tuple.Create(true, Result.RUN);
  1233. }
  1234. if (bExecute == Result.Succeed) //检查Success, next
  1235. {
  1236. next();
  1237. ExecuteResult = Tuple.Create(true, Result.RUN);
  1238. return Tuple.Create(true, Result.RUN);
  1239. }
  1240. if (bExecute == Result.FAIL) //检查 Fail 直接返回Fail
  1241. {
  1242. ExecuteResult = Tuple.Create(true, Result.FAIL);
  1243. return Tuple.Create(true, Result.FAIL);
  1244. }
  1245. }
  1246. if (timer.IsTimeout())
  1247. {
  1248. ExecuteResult = Tuple.Create(true, Result.TIMEOUT);
  1249. return Tuple.Create(true, Result.TIMEOUT);
  1250. }
  1251. ExecuteResult = Tuple.Create(true, Result.RUN);
  1252. return Tuple.Create(true, Result.RUN);
  1253. }
  1254. ExecuteResult = Tuple.Create(false, Result.RUN);
  1255. return Tuple.Create(false, Result.RUN);
  1256. }
  1257. public Tuple<bool, Result> Wait<T>(T id, IRoutine rt)
  1258. {
  1259. int idx = Convert.ToInt32(id);
  1260. bool bActive = Acitve(idx);
  1261. if (bActive)
  1262. {
  1263. if (state == STATE.IDLE)
  1264. {
  1265. rt.Start();
  1266. state = STATE.WAIT;
  1267. }
  1268. Result ret = rt.Monitor();
  1269. return Tuple.Create(true, ret);
  1270. }
  1271. return Tuple.Create(false, Result.RUN);
  1272. }
  1273. //Monitor
  1274. public Tuple<bool, Result> Monitor<T>(T id, Func<bool> func, Func<bool> check, double time)
  1275. {
  1276. int idx = Convert.ToInt32(id);
  1277. bool bActive = Acitve(idx);
  1278. bool bCheck = false;
  1279. if (bActive)
  1280. {
  1281. if (state == STATE.IDLE)
  1282. {
  1283. if ((func != null) && !func())
  1284. {
  1285. return Tuple.Create(true, Result.FAIL);
  1286. }
  1287. timer.Start(time);
  1288. state = STATE.WAIT;
  1289. }
  1290. bCheck = check();
  1291. if (!bCheck)
  1292. {
  1293. return Tuple.Create(true, Result.FAIL); //Termianate
  1294. }
  1295. if (timer.IsTimeout())
  1296. {
  1297. next();
  1298. }
  1299. return Tuple.Create(true, Result.RUN);
  1300. }
  1301. return Tuple.Create(false, Result.RUN);
  1302. }
  1303. //Delay
  1304. public Tuple<bool, Result> Delay<T>(T id, Func<bool> func, double time)
  1305. {
  1306. int idx = Convert.ToInt32(id);
  1307. bool bActive = Acitve(idx);
  1308. if (bActive)
  1309. {
  1310. //if (_currentTokenId != idx && !ExecuteResult.Item1) return ExecuteResult;
  1311. if (state == STATE.IDLE)
  1312. {
  1313. if ((func != null) && !func())
  1314. {
  1315. ExecuteResult = Tuple.Create(true, Result.FAIL);
  1316. return Tuple.Create(true, Result.FAIL);
  1317. }
  1318. _currentTokenId = idx;
  1319. timer.Start(time);
  1320. state = STATE.WAIT;
  1321. }
  1322. if (timer.IsTimeout())
  1323. {
  1324. next();
  1325. }
  1326. ExecuteResult = Tuple.Create(true, Result.RUN);
  1327. return Tuple.Create(true, Result.RUN);
  1328. }
  1329. ExecuteResult = Tuple.Create(false, Result.RUN);
  1330. return Tuple.Create(false, Result.RUN);
  1331. }
  1332. //先delay 再运行
  1333. public Tuple<bool, Result> DelayCheck<T>(T id, Func<bool> func, double time)
  1334. {
  1335. int idx = Convert.ToInt32(id);
  1336. bool bActive = Acitve(idx);
  1337. if (bActive)
  1338. {
  1339. if (state == STATE.IDLE)
  1340. {
  1341. timer.Start(time);
  1342. state = STATE.WAIT;
  1343. }
  1344. if (timer.IsTimeout())
  1345. {
  1346. if (func != null && !func())
  1347. {
  1348. return Tuple.Create(true, Result.FAIL);
  1349. }
  1350. next();
  1351. }
  1352. return Tuple.Create(true, Result.RUN);
  1353. }
  1354. return Tuple.Create(false, Result.RUN);
  1355. }
  1356. #endregion
  1357. private Tuple<bool, bool> execute(int id, Func<bool> func) //顺序执行
  1358. {
  1359. bool bActive = Acitve(id);
  1360. bool bExecute = false;
  1361. if (bActive)
  1362. {
  1363. //if (ExecuteResult.Item1) return Tuple.Create(true, true);
  1364. bExecute = func();
  1365. if (bExecute)
  1366. {
  1367. next();
  1368. }
  1369. }
  1370. return Tuple.Create(bActive, bExecute);
  1371. }
  1372. private Tuple<bool, bool> Check(int id, Func<bool> func) //check
  1373. {
  1374. bool bActive = Acitve(id);
  1375. bool bExecute = false;
  1376. if (bActive)
  1377. {
  1378. if (ExecuteResult.Item1) return Tuple.Create(true, true);
  1379. bExecute = func();
  1380. next();
  1381. }
  1382. return Tuple.Create(bActive, bExecute);
  1383. }
  1384. /// <summary>
  1385. /// </summary>
  1386. /// <param name="id"></param>
  1387. /// <param name="func"></param>
  1388. /// <param name="timeout"></param>
  1389. /// <returns>
  1390. /// item1 Active
  1391. /// item2 execute
  1392. /// item3 Timeout
  1393. ///</returns>
  1394. private Tuple<bool, bool, bool> wait(int id, Func<bool> func, double timeout = int.MaxValue) //Wait condition
  1395. {
  1396. bool bActive = Acitve(id);
  1397. bool bExecute = false;
  1398. bool bTimeout = false;
  1399. if (bActive)
  1400. {
  1401. if (state == STATE.IDLE)
  1402. {
  1403. timer.Start(timeout);
  1404. state = STATE.WAIT;
  1405. }
  1406. bExecute = func();
  1407. if (bExecute)
  1408. {
  1409. next();
  1410. }
  1411. bTimeout = timer.IsTimeout();
  1412. }
  1413. return Tuple.Create(bActive, bExecute, bTimeout);
  1414. }
  1415. private Tuple<bool, bool?, bool> wait(int id, Func<bool?> func, double timeout = int.MaxValue) //Wait condition && Check error
  1416. {
  1417. bool bActive = Acitve(id);
  1418. bool? bExecute = false;
  1419. bool bTimeout = false;
  1420. if (bActive)
  1421. {
  1422. if (state == STATE.IDLE)
  1423. {
  1424. timer.Start(timeout);
  1425. state = STATE.WAIT;
  1426. }
  1427. bExecute = func();
  1428. if (bExecute.HasValue && bExecute.Value)
  1429. {
  1430. next();
  1431. }
  1432. bTimeout = timer.IsTimeout();
  1433. }
  1434. return Tuple.Create(bActive, bExecute, bTimeout);
  1435. }
  1436. /// <summary>
  1437. /// </summary>
  1438. /// <param name="value"></param>
  1439. /// <returns>
  1440. /// item1 true, return item2
  1441. /// </returns>
  1442. private Tuple<bool, Result> Check(Tuple<bool, bool> value)
  1443. {
  1444. if (value.Item1)
  1445. {
  1446. if (!value.Item2)
  1447. {
  1448. ExecuteResult = Tuple.Create(true, Result.FAIL);
  1449. return Tuple.Create(true, Result.FAIL);
  1450. }
  1451. ExecuteResult = Tuple.Create(true, Result.RUN);
  1452. return Tuple.Create(true, Result.RUN);
  1453. }
  1454. ExecuteResult = Tuple.Create(false, Result.RUN);
  1455. return Tuple.Create(false, Result.RUN);
  1456. }
  1457. private Tuple<bool, Result> Check(Tuple<bool, bool, bool> value)
  1458. {
  1459. if (value.Item1) // 当前执行
  1460. {
  1461. if (CheckTimeout(value)) //timeout
  1462. {
  1463. return Tuple.Create(true, Result.TIMEOUT);
  1464. }
  1465. return Tuple.Create(true, Result.RUN);
  1466. }
  1467. return Tuple.Create(false, Result.RUN);
  1468. }
  1469. private Tuple<bool, Result> Check(Tuple<bool, bool?, bool> value)
  1470. {
  1471. if (value.Item1) // 当前执行
  1472. {
  1473. if (value.Item2 == null)
  1474. {
  1475. return Tuple.Create(true, Result.FAIL);
  1476. }
  1477. else
  1478. {
  1479. if (value.Item2 == false && value.Item3 == true) //timeout
  1480. {
  1481. return Tuple.Create(true, Result.TIMEOUT);
  1482. }
  1483. return Tuple.Create(true, Result.RUN);
  1484. }
  1485. }
  1486. return Tuple.Create(false, Result.RUN);
  1487. }
  1488. private bool CheckTimeout(Tuple<bool, bool, bool> value)
  1489. {
  1490. return value.Item1 == true && value.Item2 == false && value.Item3 == true;
  1491. }
  1492. private bool Acitve(int id) //
  1493. {
  1494. if (_steps.Contains(id))
  1495. return false;
  1496. this._id = id;
  1497. return true;
  1498. }
  1499. private void next()
  1500. {
  1501. _steps.Push(this._id);
  1502. state = STATE.IDLE;
  1503. }
  1504. private void next(int step) //loop
  1505. {
  1506. while (_steps.Pop() != step) ;
  1507. state = STATE.IDLE;
  1508. }
  1509. public void Delay(int id, double delaySeconds)
  1510. {
  1511. Tuple<bool, Result> ret = Delay(id, () =>
  1512. {
  1513. return true;
  1514. }, delaySeconds * 1000);
  1515. if (ret.Item1)
  1516. {
  1517. if (ret.Item2 == Result.RUN)
  1518. {
  1519. }
  1520. }
  1521. }
  1522. public bool IsActived(int id)
  1523. {
  1524. return _steps.Contains(id);
  1525. }
  1526. }
  1527. public enum LastFunctionEnum
  1528. {
  1529. PowerUp,
  1530. OpenOrReachStage,
  1531. CloseOrAutoHome,
  1532. Map = 8,
  1533. HomingCalibration = 16,
  1534. MoveCommand = 34,
  1535. }
  1536. public enum PortStateEnum
  1537. {
  1538. Unlock,
  1539. Lock,
  1540. Other,
  1541. }
  1542. public enum WaferSeaterStateEnum
  1543. {
  1544. SeaterAtHome,
  1545. SeaterOut,
  1546. None,
  1547. }
  1548. }