StateMachine.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. using System;
  2. using System.Diagnostics;
  3. using System.Threading;
  4. using System.Collections.Generic;
  5. using System.Collections.Concurrent;
  6. using Aitex.Core.RT.Log;
  7. using Aitex.Core.Util;
  8. using Aitex.Core.Utilities;
  9. using System.Threading.Tasks;
  10. using Aitex.Core.MES;
  11. using Aitex.Core.RT.SCCore;
  12. using Aitex.Core.MES.YZQZ;
  13. namespace Aitex.Core.RT.Fsm
  14. {
  15. /// <summary>
  16. /// FSM transition function
  17. /// 返回值: true 需要转换状态
  18. /// false 保持状态不变
  19. /// </summary>
  20. /// <param name="param"></param>
  21. /// <returns></returns>
  22. public enum FSM_MSG
  23. {
  24. TIMER = 0x0FFFFFF0,
  25. NONE,
  26. WARNING,
  27. ALARM,
  28. }
  29. public enum FSM_STATE
  30. {
  31. UNDEFINE = 0x0FFFFFF0,
  32. SAME,
  33. ANY,
  34. }
  35. public class StateMachine<T> : IStateMachine
  36. {
  37. public string Name { get; set; }
  38. public int ElapsedTime
  39. {
  40. get
  41. {
  42. int ticket = Environment.TickCount;
  43. return ticket > enterTime ? ticket - enterTime : 0x7FFFFFFF + ticket - enterTime;
  44. }
  45. }
  46. public int EnterTime { set { enterTime = value; } }
  47. public int State { get; set; }
  48. public int PrevState { get; set; }
  49. private bool _enableRepeatedMsg;
  50. public int MaxMsgInQueue { get; set; }
  51. private int enterTime;
  52. private int interval;
  53. private CancellationTokenSource cancelToken;
  54. private BlockingCollection<KeyValuePair<int, object[]>> msgQuene;
  55. private KeyValuePair<int, object[]> timeoutMsg = new KeyValuePair<int, object[]>((int)FSM_MSG.TIMER, null);
  56. /// <summary>
  57. /// 状态迁移表 当前状态, 消息, 函数, 迁移状态
  58. /// AnyState迁移表 消息, 函数, 迁移状态
  59. /// 状态进入/退出迁移表 状态,进入函数,进入消息,退出函数,
  60. /// </summary>
  61. private Dictionary<int, Dictionary<int, Tuple<FsmFunc, int>>> transition;
  62. private Dictionary<int, Tuple<FsmFunc, int>> anyStateTransition;
  63. private Dictionary<int, Tuple<FsmFunc, int, FsmFunc>> enterExitTransition;
  64. private Dictionary<int, string> _stringState = new Dictionary<int, string>();
  65. private Dictionary<int, string> _stringMessage = new Dictionary<int, string>();
  66. DeviceTimer _loopTimer = new DeviceTimer();
  67. public StateMachine(string name, int initState = (int)FSM_STATE.UNDEFINE, int interval = 100)
  68. {
  69. Name = name + " FSM";
  70. MaxMsgInQueue = 500;
  71. this.State = initState;
  72. this.PrevState = initState;
  73. this.interval = interval;
  74. cancelToken = new CancellationTokenSource();
  75. msgQuene = new BlockingCollection<KeyValuePair<int, object[]>>();
  76. transition = new Dictionary<int, Dictionary<int, Tuple<FsmFunc, int>>>();
  77. anyStateTransition = new Dictionary<int, Tuple<FsmFunc, int>>();
  78. enterExitTransition = new Dictionary<int, Tuple<FsmFunc, int, FsmFunc>>();
  79. EnumLoop<FSM_STATE>.ForEach((item) =>
  80. {
  81. MapState((int)item, item.ToString());
  82. });
  83. EnumLoop<FSM_MSG>.ForEach((item) =>
  84. {
  85. MapMessage((int)item, item.ToString());
  86. });
  87. }
  88. #region Interface
  89. public void Start()
  90. {
  91. OnEnterState(this.State);
  92. }
  93. public void Loop()
  94. {
  95. while (!cancelToken.IsCancellationRequested)
  96. {
  97. KeyValuePair<int, object[]> msg = timeoutMsg;
  98. try
  99. {
  100. int timeout = interval - (int)_loopTimer.GetElapseTime();
  101. if (timeout < 50)
  102. timeout = 50;
  103. if (!msgQuene.TryTake(out msg, timeout, cancelToken.Token))
  104. msg = timeoutMsg;
  105. _loopTimer.Start(0);
  106. //Loop AnyState迁移表
  107. if (anyStateTransition.ContainsKey(msg.Key))
  108. {
  109. if (anyStateTransition[msg.Key].Item1 != null)
  110. {
  111. if (anyStateTransition[msg.Key].Item1(msg.Value)) //need ChangeState
  112. {
  113. if (anyStateTransition[msg.Key].Item2 != State && anyStateTransition[msg.Key].Item2 != (int)FSM_STATE.SAME)
  114. {
  115. OnExitState((int)FSM_STATE.ANY);
  116. OnExitState(State);
  117. enterTime = Environment.TickCount;
  118. PrevState = State;
  119. State = anyStateTransition[msg.Key].Item2;
  120. OnEnterState((int)FSM_STATE.ANY);
  121. OnEnterState((int)State);
  122. }
  123. }
  124. }
  125. continue;
  126. }
  127. if (!transition.ContainsKey(State))
  128. {
  129. if (msg.Key != (int)FSM_MSG.TIMER)
  130. {
  131. LOG.Warning("状态机{0}未定义在状态{1}时处理方法。", Name, GetStringState(State));
  132. }
  133. continue;
  134. }
  135. if (!transition[State].ContainsKey(msg.Key))
  136. {
  137. if (msg.Key != (int)FSM_MSG.TIMER)
  138. {
  139. LOG.Warning("状态机{0}未定义在状态{1}时收到消息{2}的处理方法。", Name, GetStringState(State), GetStringMessage(msg.Key));
  140. }
  141. continue;
  142. }
  143. //Loop Transition
  144. //if fun is null or fun return true need change
  145. if (transition[State][msg.Key].Item1 == null || transition[State][msg.Key].Item1(msg.Value))
  146. {
  147. if (transition[State][msg.Key].Item2 != State && transition[State][msg.Key].Item2 != (int)FSM_STATE.SAME)
  148. {
  149. OnExitState((int)FSM_STATE.ANY);
  150. OnExitState(State);
  151. enterTime = Environment.TickCount;
  152. PrevState = State;
  153. State = transition[State][msg.Key].Item2;
  154. OnEnterState((int)FSM_STATE.ANY);
  155. OnEnterState((int)State);
  156. postYZQZMachineStatus((int)State);
  157. }
  158. }
  159. }
  160. catch (OperationCanceledException ex)
  161. {
  162. LOG.Error("FSM cancel", ex);
  163. }
  164. catch (Exception ex)
  165. {
  166. LOG.Error(String.Format("{0}: State {1},Msg{2} Loop has exception ", Name, GetStringState(State), GetStringMessage(msg.Key)), ex);
  167. try
  168. {
  169. StackFrame sf = new StackTrace(true).GetFrame(3);
  170. LOG.Error(string.Format("State Machine running error in {0}, {1}",
  171. sf.GetFileLineNumber() ,
  172. sf.GetMethod().Name));
  173. }
  174. catch (Exception)
  175. {
  176. }
  177. }
  178. }
  179. }
  180. private async void postYZQZMachineStatus(int state)
  181. {
  182. await Task.Run(() => {
  183. Fab fb = (Fab)Enum.Parse(typeof(Fab), SC.GetValue<int>(SCName.System_Company).ToString());
  184. if (fb == Fab.YZQZ)
  185. {
  186. FabAutoComm com = new YZQZFabAuto();
  187. com.SaveMachineStatusRecord(state);
  188. }
  189. });
  190. }
  191. public void Stop()
  192. {
  193. cancelToken.Cancel();
  194. }
  195. string GetStringState(int state)
  196. {
  197. if (_stringState.ContainsKey(state))
  198. return _stringState[state];
  199. return state.ToString();
  200. }
  201. string GetStringMessage(int message)
  202. {
  203. if (_stringMessage.ContainsKey(message))
  204. return _stringMessage[message];
  205. return message.ToString();
  206. }
  207. public void MapState(int state, string stringState)
  208. {
  209. System.Diagnostics.Debug.Assert(!_stringState.ContainsKey(state));
  210. _stringState[state] = stringState;
  211. }
  212. public void MapMessage(int message, string stringMessage)
  213. {
  214. System.Diagnostics.Debug.Assert(!_stringMessage.ContainsKey(message));
  215. _stringMessage[message] = stringMessage;
  216. }
  217. public bool FindTransition(int state, int msg)
  218. {
  219. if (anyStateTransition.ContainsKey(msg))
  220. return true;
  221. if (transition.ContainsKey(state) && transition[state] != null)
  222. {
  223. Dictionary<int, Tuple<FsmFunc, int>> table = transition[state];
  224. if (table.ContainsKey(msg))
  225. return true;
  226. }
  227. return false;
  228. }
  229. public void Transition(int state, int msg, FsmFunc func, int next)
  230. {
  231. if (!transition.ContainsKey(state) || transition[state] == null)
  232. {
  233. transition[state] = new Dictionary<int, Tuple<FsmFunc, int>>();
  234. }
  235. transition[state][msg] = new Tuple<FsmFunc, int>(func, next);
  236. }
  237. public void AnyStateTransition(int msg, FsmFunc func, int next)
  238. {
  239. anyStateTransition[msg] = new Tuple<FsmFunc, int>(func, next);
  240. }
  241. public void EnterExitTransition(int state, FsmFunc enter, int msg, FsmFunc exit)
  242. {
  243. enterExitTransition[state] = new Tuple<FsmFunc, int, FsmFunc>(enter, msg, exit);
  244. }
  245. public void EnableRepeatedMsg(bool enable)
  246. {
  247. _enableRepeatedMsg = enable;
  248. }
  249. public void PostMsg(int msg, params object[] args)
  250. {
  251. foreach (var item in msgQuene)
  252. {
  253. if (item.Key == msg && !_enableRepeatedMsg)
  254. {
  255. if (msg != (int)FSM_MSG.WARNING && msg != (int)FSM_MSG.ALARM)
  256. LOG.Warning("状态机【{0}】收到重复发送的消息{1},该条消息被忽略。",Name, msg);
  257. return;
  258. }
  259. }
  260. if (msgQuene.Count > MaxMsgInQueue)
  261. {
  262. LOG.Warning("状态机【{0}】收到 的消息超过{1}条,消息{2}被忽略。",Name, MaxMsgInQueue, msg);
  263. }
  264. msgQuene.Add(new KeyValuePair<int, object[]>(msg, args));
  265. }
  266. #endregion
  267. private void OnEnterState(int state)
  268. {
  269. if (enterExitTransition.ContainsKey(state))
  270. {
  271. if (enterExitTransition[state].Item1 != null)
  272. {
  273. enterExitTransition[state].Item1(null);
  274. }
  275. if (enterExitTransition[state].Item2 != (int)FSM_MSG.NONE)
  276. {
  277. PostMsg(enterExitTransition[state].Item2, null);
  278. }
  279. }
  280. }
  281. private void OnExitState(int state)
  282. {
  283. if (enterExitTransition.ContainsKey(state))
  284. {
  285. if (enterExitTransition[state].Item3 != null)
  286. {
  287. enterExitTransition[state].Item3(null);
  288. }
  289. }
  290. }
  291. }
  292. }