StateMachine.cs 15 KB

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