StateMachine.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  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. TraceState(PrevState, State, "anyStateTransition 过程");
  134. }
  135. }
  136. }
  137. if (_msgInProcess.Key != timeoutMsg.Key)
  138. {
  139. Interlocked.Decrement(ref _msgCounter);
  140. //System.Diagnostics.Trace.WriteLine($"message out1: {Name}--> {_msgCounter}");
  141. }
  142. continue;
  143. }
  144. if (!transition.ContainsKey(State))
  145. {
  146. if (_msgInProcess.Key != (int)FSM_MSG.TIMER)
  147. {
  148. LOG.Warning($"StateMachine [{Name}] no definition of state [{GetStringState(State)}] ");
  149. }
  150. if (_msgInProcess.Key != timeoutMsg.Key)
  151. {
  152. Interlocked.Decrement(ref _msgCounter);
  153. //System.Diagnostics.Trace.WriteLine($"message out2: {Name} --> {_msgCounter}");
  154. }
  155. continue;
  156. }
  157. if (!transition[State].ContainsKey(_msgInProcess.Key))
  158. {
  159. if (_msgInProcess.Key != (int)FSM_MSG.TIMER)
  160. {
  161. LOG.Warning($"StateMachine {Name} no definition of [state={GetStringState(State)}], [message={GetStringMessage(_msgInProcess.Key)}]");
  162. }
  163. if (_msgInProcess.Key != timeoutMsg.Key)
  164. {
  165. Interlocked.Decrement(ref _msgCounter);
  166. // System.Diagnostics.Trace.WriteLine($"message out3:{Name}--> {_msgCounter}");
  167. }
  168. continue;
  169. }
  170. //Loop Transition
  171. //if fun is null or fun return true need change
  172. if (transition[State][_msgInProcess.Key].Item1 == null || transition[State][_msgInProcess.Key].Item1(_msgInProcess.Value))
  173. {
  174. if (transition[State][_msgInProcess.Key].Item2 != State && transition[State][_msgInProcess.Key].Item2 != (int)FSM_STATE.SAME)
  175. {
  176. OnExitState((int)FSM_STATE.ANY);
  177. OnExitState(State);
  178. enterTime = Environment.TickCount;
  179. PrevState = State;
  180. State = transition[State][_msgInProcess.Key].Item2;
  181. OnEnterState((int)FSM_STATE.ANY);
  182. OnEnterState((int)State);
  183. TraceState(PrevState, State, "transition 过程");
  184. }
  185. }
  186. if (_msgInProcess.Key != timeoutMsg.Key)
  187. {
  188. Interlocked.Decrement(ref _msgCounter);
  189. //System.Diagnostics.Trace.WriteLine($"message out4: {Name}--> {_msgCounter}");
  190. }
  191. _msgInProcess = timeoutMsg;
  192. }
  193. catch (OperationCanceledException)
  194. {
  195. LOG.Info($"FSM {Name} is canceled");
  196. }
  197. catch (Exception ex)
  198. {
  199. LOG.Error(ex.StackTrace, ex);
  200. }
  201. }
  202. }
  203. public void Stop()
  204. {
  205. cancelToken.Cancel();
  206. }
  207. string GetStringState(int state)
  208. {
  209. if (_stringState.ContainsKey(state))
  210. return _stringState[state];
  211. return state.ToString();
  212. }
  213. string GetStringMessage(int message)
  214. {
  215. if (_stringMessage.ContainsKey(message))
  216. return _stringMessage[message];
  217. return message.ToString();
  218. }
  219. public void MapState(int state, string stringState)
  220. {
  221. System.Diagnostics.Debug.Assert(!_stringState.ContainsKey(state));
  222. _stringState[state] = stringState;
  223. }
  224. public void MapMessage(int message, string stringMessage)
  225. {
  226. System.Diagnostics.Debug.Assert(!_stringMessage.ContainsKey(message));
  227. _stringMessage[message] = stringMessage;
  228. }
  229. public bool FindTransition(int state, int msg)
  230. {
  231. if (anyStateTransition.ContainsKey(msg))
  232. return true;
  233. if (transition.ContainsKey(state) && transition[state] != null)
  234. {
  235. Dictionary<int, Tuple<FsmFunc, int>> table = transition[state];
  236. if (table.ContainsKey(msg))
  237. return true;
  238. }
  239. return false;
  240. }
  241. public void Transition(int state, int msg, FsmFunc func, int next)
  242. {
  243. if (!transition.ContainsKey(state) || transition[state] == null)
  244. {
  245. transition[state] = new Dictionary<int, Tuple<FsmFunc, int>>();
  246. }
  247. transition[state][msg] = new Tuple<FsmFunc, int>(func, next);
  248. }
  249. public void AnyStateTransition(int msg, FsmFunc func, int next)
  250. {
  251. anyStateTransition[msg] = new Tuple<FsmFunc, int>(func, next);
  252. }
  253. public void EnterExitTransition(int state, FsmFunc enter, int msg, FsmFunc exit)
  254. {
  255. enterExitTransition[state] = new Tuple<FsmFunc, int, FsmFunc>(enter, msg, exit);
  256. }
  257. private const string PMBName = "PMB";
  258. private const string PMAName = "PMA";
  259. private const string TMName = "TM";
  260. private void TraceState(int prevState, int afterState, string title)
  261. {
  262. //if (Name != null && (Name.IndexOf(PMBName) > -1 || Name.IndexOf(PMAName) > -1 || Name.IndexOf(TMName) > -1))
  263. if (Name != null)
  264. {
  265. string preStateContent = _stringState.ContainsKey(prevState) ? _stringState[prevState] : prevState.ToString();
  266. string postStateContent = _stringState.ContainsKey(afterState)? _stringState[afterState] : afterState.ToString();
  267. LOG.Info($"StateMachine Name={Name} 状态转换前={preStateContent} 转换后={postStateContent} by {title}");
  268. }
  269. }
  270. public void PostMsg(int msg, params object[] args)
  271. {
  272. Interlocked.Increment(ref _msgCounter);
  273. //lock (_lockerMsgQueue)
  274. {
  275. _msgQueue.Add(new KeyValuePair<int, object[]>(msg, args));
  276. }
  277. //System.Diagnostics.Trace.WriteLine($"PostMsg: {msg}--> {_msgCounter}");
  278. }
  279. public void PostMsgWithoutLock(int msg, params object[] args)
  280. {
  281. Interlocked.Increment(ref _msgCounter);
  282. _msgQueue.Add(new KeyValuePair<int, object[]>(msg, args));
  283. //System.Diagnostics.Trace.WriteLine($"PostMsgWithoutLock: {msg}--> {_msgCounter}");
  284. }
  285. #endregion
  286. private void OnEnterState(int state)
  287. {
  288. if (enterExitTransition.ContainsKey(state))
  289. {
  290. if (enterExitTransition[state].Item1 != null)
  291. {
  292. enterExitTransition[state].Item1(null);
  293. }
  294. if (enterExitTransition[state].Item2 != (int)FSM_MSG.NONE)
  295. {
  296. PostMsg(enterExitTransition[state].Item2, null);
  297. }
  298. }
  299. }
  300. private void OnExitState(int state)
  301. {
  302. if (enterExitTransition.ContainsKey(state))
  303. {
  304. if (enterExitTransition[state].Item3 != null)
  305. {
  306. enterExitTransition[state].Item3(null);
  307. }
  308. }
  309. }
  310. public bool CheckExecuted(int msg)
  311. {
  312. return _msgCounter == 0;
  313. //lock (_lockerMsgQueue)
  314. //{
  315. // foreach (var keyValuePair in _msgQueue)
  316. // {
  317. // if (keyValuePair.Key == msg)
  318. // return false;
  319. // }
  320. // if (_msgInProcess.Key == msg)
  321. // return false;
  322. //}
  323. //return true;
  324. }
  325. public bool CheckExecuted()
  326. {
  327. //System.Diagnostics.Trace.WriteLine($"CheckExecuted: --> {_msgCounter}");
  328. return _msgCounter == 0;
  329. //return Interlocked.CompareExchange(ref _msgCounter, 0, 0) == 0;
  330. ////lock (_lockerMsgQueue)
  331. //{
  332. // return _msgQueue.Count == 0 && _msgInProcess.Key==(int)FSM_MSG.TIMER;
  333. //}
  334. }
  335. public bool CheckExecuted(int msg, out int currentMsg, out List<int> msgQueue)
  336. {
  337. currentMsg = 0;
  338. msgQueue = new List<int>();
  339. return _msgCounter == 0;
  340. //lock (_lockerMsgQueue)
  341. //{
  342. // currentMsg = 0;
  343. // msgQueue = new List<int>();
  344. // foreach (var keyValuePair in _msgQueue)
  345. // {
  346. // if (keyValuePair.Key == msg)
  347. // return false;
  348. // msgQueue.Add(keyValuePair.Key);
  349. // }
  350. // if (_msgInProcess.Key == msg)
  351. // {
  352. // return false;
  353. // }
  354. // currentMsg = _msgInProcess.Key;
  355. //}
  356. //return true;
  357. }
  358. }
  359. }