StateMachine.cs 15 KB

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