StateMachine.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  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 : StateMachine<object>
  31. {
  32. public StateMachine(string name = "FSM", int initState = (int)FSM_STATE.UNDEFINE, int interval = 100) : base(name, initState, interval)
  33. {
  34. }
  35. }
  36. public class StateMachine<T> : IStateMachine
  37. {
  38. public string Name { get; set; }
  39. public int ElapsedTime
  40. {
  41. get
  42. {
  43. int ticket = Environment.TickCount;
  44. return ticket > enterTime ? ticket - enterTime : 0x7FFFFFFF + ticket - enterTime;
  45. }
  46. }
  47. public int EnterTime { set { enterTime = value; } }
  48. public int State { get; set; }
  49. public int PrevState { get; set; }
  50. public int LastMsg { get; private set; }
  51. private int enterTime;
  52. private int interval;
  53. private CancellationTokenSource cancelToken;
  54. private BlockingCollection<KeyValuePair<int, object[]>> _msgQueue;
  55. private object _lockerMsgQueue = new object();
  56. private KeyValuePair<int, object[]> timeoutMsg = new KeyValuePair<int, object[]>((int)FSM_MSG.TIMER, null);
  57. /// <summary>
  58. /// 状态迁移表 当前状态, 消息, 函数, 迁移状态
  59. /// AnyState迁移表 消息, 函数, 迁移状态
  60. /// 状态进入/退出迁移表 状态,进入函数,进入消息,退出函数,
  61. /// </summary>
  62. private Dictionary<int, Dictionary<int, Tuple<FsmFunc, int>>> transition;
  63. private Dictionary<int, Tuple<FsmFunc, int>> anyStateTransition;
  64. private Dictionary<int, Tuple<FsmFunc, int, FsmFunc>> enterExitTransition;
  65. private Dictionary<int, string> _stringState = new Dictionary<int, string>();
  66. private Dictionary<int, string> _stringMessage = new Dictionary<int, string>();
  67. private KeyValuePair<int, object[]> _msgInProcess = new KeyValuePair<int, object[]>((int)FSM_MSG.TIMER, null);
  68. private long _msgCounter = 0;
  69. public StateMachine(string name, int initState = (int)FSM_STATE.UNDEFINE, int interval = 100)
  70. {
  71. Name = name + " FSM";
  72. this.State = initState;
  73. this.PrevState = initState;
  74. this.interval = interval;
  75. cancelToken = new CancellationTokenSource();
  76. _msgQueue = new BlockingCollection<KeyValuePair<int, object[]>>();
  77. transition = new Dictionary<int, Dictionary<int, Tuple<FsmFunc, int>>>();
  78. anyStateTransition = new Dictionary<int, Tuple<FsmFunc, int>>();
  79. enterExitTransition = new Dictionary<int, Tuple<FsmFunc, int, FsmFunc>>();
  80. EnumLoop<FSM_STATE>.ForEach((item) =>
  81. {
  82. MapState((int)item, item.ToString());
  83. });
  84. EnumLoop<FSM_MSG>.ForEach((item) =>
  85. {
  86. MapMessage((int)item, item.ToString());
  87. });
  88. }
  89. #region Interface
  90. public void Init(int initState, int intervalTimeMs)
  91. {
  92. State = initState;
  93. interval = intervalTimeMs;
  94. }
  95. public void Start()
  96. {
  97. OnEnterState(this.State);
  98. }
  99. public void Loop()
  100. {
  101. while (!cancelToken.IsCancellationRequested)
  102. {
  103. //_msgInProcess = timeoutMsg;
  104. try
  105. {
  106. KeyValuePair<int, object[]> msg = timeoutMsg;
  107. lock (_lockerMsgQueue)
  108. {
  109. if (!_msgQueue.TryTake(out msg, interval, cancelToken.Token))
  110. _msgInProcess = timeoutMsg;
  111. else
  112. {
  113. _msgInProcess = msg;
  114. }
  115. }
  116. //Loop AnyState迁移表
  117. if (anyStateTransition.ContainsKey(_msgInProcess.Key))
  118. {
  119. if (anyStateTransition[_msgInProcess.Key].Item1 != null)
  120. {
  121. if (anyStateTransition[_msgInProcess.Key].Item1(_msgInProcess.Value)) //need ChangeState
  122. {
  123. if (anyStateTransition[_msgInProcess.Key].Item2 != State && anyStateTransition[_msgInProcess.Key].Item2 != (int)FSM_STATE.SAME)
  124. {
  125. OnExitState((int)FSM_STATE.ANY);
  126. OnExitState(State);
  127. enterTime = Environment.TickCount;
  128. LastMsg = msg.Key;
  129. PrevState = State;
  130. State = anyStateTransition[_msgInProcess.Key].Item2;
  131. OnEnterState((int)FSM_STATE.ANY);
  132. OnEnterState((int)State);
  133. }
  134. }
  135. }
  136. if (_msgInProcess.Key != timeoutMsg.Key)
  137. {
  138. Interlocked.Decrement(ref _msgCounter);
  139. //System.Diagnostics.Trace.WriteLine($"message out1: {Name}--> {_msgCounter}");
  140. }
  141. continue;
  142. }
  143. if (!transition.ContainsKey(State))
  144. {
  145. if (_msgInProcess.Key != (int)FSM_MSG.TIMER)
  146. {
  147. LOG.Warning($"StateMachine [{Name}] no definition of state [{GetStringState(State)}] ");
  148. }
  149. if (_msgInProcess.Key != timeoutMsg.Key)
  150. {
  151. Interlocked.Decrement(ref _msgCounter);
  152. //System.Diagnostics.Trace.WriteLine($"message out2: {Name} --> {_msgCounter}");
  153. }
  154. continue;
  155. }
  156. if (!transition[State].ContainsKey(_msgInProcess.Key))
  157. {
  158. if (_msgInProcess.Key != (int)FSM_MSG.TIMER)
  159. {
  160. LOG.Warning($"StateMachine {Name} no definition of [state={GetStringState(State)}], [message={GetStringMessage(_msgInProcess.Key)}]");
  161. }
  162. if (_msgInProcess.Key != timeoutMsg.Key)
  163. {
  164. Interlocked.Decrement(ref _msgCounter);
  165. // System.Diagnostics.Trace.WriteLine($"message out3:{Name}--> {_msgCounter}");
  166. }
  167. continue;
  168. }
  169. //Loop Transition
  170. //if fun is null or fun return true need change
  171. if (transition[State][_msgInProcess.Key].Item1 == null || transition[State][_msgInProcess.Key].Item1(_msgInProcess.Value))
  172. {
  173. if (transition[State][_msgInProcess.Key].Item2 != State && transition[State][_msgInProcess.Key].Item2 != (int)FSM_STATE.SAME)
  174. {
  175. OnExitState((int)FSM_STATE.ANY);
  176. OnExitState(State);
  177. enterTime = Environment.TickCount;
  178. PrevState = State;
  179. State = transition[State][_msgInProcess.Key].Item2;
  180. OnEnterState((int)FSM_STATE.ANY);
  181. OnEnterState((int)State);
  182. }
  183. }
  184. if (_msgInProcess.Key != timeoutMsg.Key)
  185. {
  186. Interlocked.Decrement(ref _msgCounter);
  187. //System.Diagnostics.Trace.WriteLine($"message out4: {Name}--> {_msgCounter}");
  188. }
  189. _msgInProcess = timeoutMsg;
  190. }
  191. catch (OperationCanceledException)
  192. {
  193. LOG.Info($"FSM {Name} is canceled");
  194. }
  195. catch (Exception ex)
  196. {
  197. LOG.Error(ex.StackTrace, ex);
  198. }
  199. }
  200. }
  201. public void Stop()
  202. {
  203. cancelToken.Cancel();
  204. }
  205. string GetStringState(int state)
  206. {
  207. if (_stringState.ContainsKey(state))
  208. return _stringState[state];
  209. return state.ToString();
  210. }
  211. string GetStringMessage(int message)
  212. {
  213. if (_stringMessage.ContainsKey(message))
  214. return _stringMessage[message];
  215. return message.ToString();
  216. }
  217. public void MapState(int state, string stringState)
  218. {
  219. System.Diagnostics.Debug.Assert(!_stringState.ContainsKey(state));
  220. _stringState[state] = stringState;
  221. }
  222. public void MapMessage(int message, string stringMessage)
  223. {
  224. System.Diagnostics.Debug.Assert(!_stringMessage.ContainsKey(message));
  225. _stringMessage[message] = stringMessage;
  226. }
  227. public bool FindTransition(int state, int msg)
  228. {
  229. if (anyStateTransition.ContainsKey(msg))
  230. return true;
  231. if (transition.ContainsKey(state) && transition[state] != null)
  232. {
  233. Dictionary<int, Tuple<FsmFunc, int>> table = transition[state];
  234. if (table.ContainsKey(msg))
  235. return true;
  236. }
  237. return false;
  238. }
  239. public void Transition(int state, int msg, FsmFunc func, int next)
  240. {
  241. if (!transition.ContainsKey(state) || transition[state] == null)
  242. {
  243. transition[state] = new Dictionary<int, Tuple<FsmFunc, int>>();
  244. }
  245. transition[state][msg] = new Tuple<FsmFunc, int>(func, next);
  246. }
  247. public void AnyStateTransition(int msg, FsmFunc func, int next)
  248. {
  249. anyStateTransition[msg] = new Tuple<FsmFunc, int>(func, next);
  250. }
  251. public void EnterExitTransition(int state, FsmFunc enter, int msg, FsmFunc exit)
  252. {
  253. enterExitTransition[state] = new Tuple<FsmFunc, int, FsmFunc>(enter, msg, exit);
  254. }
  255. public void PostMsg(int msg, params object[] args)
  256. {
  257. Interlocked.Increment(ref _msgCounter);
  258. //lock (_lockerMsgQueue)
  259. {
  260. _msgQueue.Add(new KeyValuePair<int, object[]>(msg, args));
  261. }
  262. //System.Diagnostics.Trace.WriteLine($"PostMsg: {msg}--> {_msgCounter}");
  263. }
  264. public void PostMsgWithoutLock(int msg, params object[] args)
  265. {
  266. Interlocked.Increment(ref _msgCounter);
  267. _msgQueue.Add(new KeyValuePair<int, object[]>(msg, args));
  268. //System.Diagnostics.Trace.WriteLine($"PostMsgWithoutLock: {msg}--> {_msgCounter}");
  269. }
  270. #endregion
  271. private void OnEnterState(int state)
  272. {
  273. if (enterExitTransition.ContainsKey(state))
  274. {
  275. if (enterExitTransition[state].Item1 != null)
  276. {
  277. enterExitTransition[state].Item1(null);
  278. }
  279. if (enterExitTransition[state].Item2 != (int)FSM_MSG.NONE)
  280. {
  281. PostMsg(enterExitTransition[state].Item2, null);
  282. }
  283. }
  284. }
  285. private void OnExitState(int state)
  286. {
  287. if (enterExitTransition.ContainsKey(state))
  288. {
  289. if (enterExitTransition[state].Item3 != null)
  290. {
  291. enterExitTransition[state].Item3(null);
  292. }
  293. }
  294. }
  295. public bool CheckExecuted(int msg)
  296. {
  297. return _msgCounter == 0;
  298. //lock (_lockerMsgQueue)
  299. //{
  300. // foreach (var keyValuePair in _msgQueue)
  301. // {
  302. // if (keyValuePair.Key == msg)
  303. // return false;
  304. // }
  305. // if (_msgInProcess.Key == msg)
  306. // return false;
  307. //}
  308. //return true;
  309. }
  310. public bool CheckExecuted()
  311. {
  312. //System.Diagnostics.Trace.WriteLine($"CheckExecuted: --> {_msgCounter}");
  313. return _msgCounter == 0;
  314. //return Interlocked.CompareExchange(ref _msgCounter, 0, 0) == 0;
  315. ////lock (_lockerMsgQueue)
  316. //{
  317. // return _msgQueue.Count == 0 && _msgInProcess.Key==(int)FSM_MSG.TIMER;
  318. //}
  319. }
  320. public bool CheckExecuted(int msg, out int currentMsg, out List<int> msgQueue)
  321. {
  322. currentMsg = 0;
  323. msgQueue = new List<int>();
  324. return _msgCounter == 0;
  325. //lock (_lockerMsgQueue)
  326. //{
  327. // currentMsg = 0;
  328. // msgQueue = new List<int>();
  329. // foreach (var keyValuePair in _msgQueue)
  330. // {
  331. // if (keyValuePair.Key == msg)
  332. // return false;
  333. // msgQueue.Add(keyValuePair.Key);
  334. // }
  335. // if (_msgInProcess.Key == msg)
  336. // {
  337. // return false;
  338. // }
  339. // currentMsg = _msgInProcess.Key;
  340. //}
  341. //return true;
  342. }
  343. }
  344. }