StateMachine.cs 12 KB

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