StateMachine.cs 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089
  1. #region --------------- Copyright Dresser Wayne Pignone -------------
  2. /*
  3. * $Log: /Wrk/WayneLibraries/Wrk/StateEngine/StateMachine.cs $
  4. *
  5. * 22 08-09-19 11:05 roger.månsson
  6. *
  7. * 21 08-03-25 14:15 Mattias.larsson
  8. * Clean-up.
  9. *
  10. * 20 08-03-25 10:32 Mattias.larsson
  11. * Ensure debugLogger is not null.
  12. *
  13. * 19 08-03-19 11:44 roger.månsson
  14. *
  15. * 18 08-03-19 11:40 roger.månsson
  16. * Fixes after code review. Added some lock protections.
  17. *
  18. * 17 08-03-19 11:15 roger.månsson
  19. * Made timer debug logging Maximized.
  20. *
  21. * 16 08-03-19 9:19 roger.månsson
  22. * Removed debug code that caused compiler warning.
  23. *
  24. * 15 08-03-18 11:10 roger.månsson
  25. * Each timer does not have it's own real timer anymore. Instead there are
  26. * a pool of timers in the StateMachine that can be shared among the
  27. * timers in the same state machine.
  28. *
  29. * 14 08-03-10 14:59 Mattias.larsson
  30. * Removed Paused and StepEvent().
  31. *
  32. * 13 08-02-26 14:14 Mattias.larsson
  33. * Added LogNameKind.
  34. * Renamed stateName to stateFactoryName.
  35. *
  36. * 12 08-01-23 16:34 Mattias.larsson
  37. *
  38. * 11 07-10-28 14:48 roger.månsson
  39. * Check if currentState is null before exiting it.
  40. *
  41. * 10 07-09-26 10:51 roger.månsson
  42. * Throw exception if a state object not can be created by any of the
  43. * state factories.
  44. *
  45. * 9 07-09-06 7:33 roger.månsson
  46. * Removed the OnLog event finally, so we can get rid of the warnings.
  47. *
  48. * 8 07-08-17 15:46 roger.månsson
  49. * Made Initialize() method public, so the state machine can be built up
  50. * of state objects without starting it.
  51. *
  52. * 7 07-08-15 15:29 roger.månsson
  53. * Support for new debug log feature. Misc shutdown fixes.
  54. *
  55. * 6 07-08-07 8:26 Mattias.larsson
  56. *
  57. * 5 07-03-12 15:17 roger.månsson
  58. * Documentation update.
  59. *
  60. * 4 07-03-12 15:00 roger.månsson
  61. * Implement a Create method that can create both threaded and synchronous
  62. * state machines.
  63. */
  64. #endregion
  65. #region Old change history
  66. /*===============================================================================
  67. * Change history
  68. * When Who Comment
  69. * ---------- ------ ------------------------------------
  70. * 2006-08-08 RMa Added a predicate-based RemovePendingEvents method.
  71. * 2006-08-08 RMa Added LogType to the log event args.
  72. * 2006-07-18 RMa Major changes, StateMachine is now abstract base class, moved out logic to sub classes CompositeStateMachine,
  73. * RootStateMachine, ThreadedRootStateMachine. Changed transition handling and event handling.
  74. * 2006-07-03 MLa Added Transition in StateChangedEventArgs
  75. * 2006-05-17 RMa Replaced diagnostic logging with OnLog event. Now it is up to the application
  76. * how the logging should be performed (preferrably using the Wayne.Lib.Log.Logger class)
  77. * 2006-05-09 RMa Changed dispose implementation, Obsoleted Stop() method. Use Dispose() instead.
  78. * 2006-04-26 RMa Moved out StateChangedEventArgs to its own source file. Implemented IDisposable correctly.
  79. * 2006-03-02 RMa FXCop updates: Changed delegate for the OnStateChanged event. Misc updates.
  80. * 2006-02-23 RMa Added time to logging.
  81. * 2006-02-03 RMa FXCop updates: Implement IDisposable, set internal messages as handled + misc.
  82. * 2006-02-01 RMa Check if the state machine is running before stopping it in the destructor.
  83. * 2006-01-27 RMa Removed interface Event. Use Event class instead.
  84. * 2006-01-09 RMa Create all state objects at startup, otherwise explicit transitions will not work.
  85. * Changed some of the explicit transition handling.
  86. * 2006-01-06 RMa Added handling of Explicit transititions.
  87. * Handle transitions asynchronously via the message thread.
  88. * 2005-12-14 RMa Changed so Internal_Enter is called by the state machine, so we are sure
  89. * that the internal stuff gets called ,if the user forgets to call base.Enter()....
  90. * 2005-12-09 RMa Added IncomingEvent without the highpriority flag that not is used anyway.
  91. * Changed the Init transition so it uses the BasicTransitionType.Init istead of the sting "Init" as type.
  92. * 2005-12-09 RMa Fixed some issues with initial state entries.
  93. * 2005-12-05 RMa This header added.
  94. *
  95. ---------------------------------------------------------------------------------*/
  96. #endregion
  97. using System;
  98. using System.Collections.Generic;
  99. using System.Linq;
  100. using Wayne.Lib.Log;
  101. namespace Wayne.Lib.StateEngine
  102. {
  103. /// <summary>
  104. /// State machine is the core engine in the Wayne.Lib.StateEngine model. It contains the states, contains the
  105. /// information about the state- transition lookup table, and handles the external and internal events.
  106. /// Normally it should not be neccesary to override this class.
  107. /// </summary>
  108. //[System.Diagnostics.DebuggerNonUserCode()]
  109. public abstract class StateMachine : IEventConsumer, IDisposable
  110. {
  111. #region Fields
  112. private const bool TimerWrapperCaching = false;
  113. private InitialState initialState;
  114. private Dictionary<string, State> createdStates = new Dictionary<string, State>();
  115. private State currentState;
  116. private StateTransitionLookup stateLookup;
  117. internal StateFactories stateFactories = new StateFactories();
  118. private StateTypeContainer stateTypeContainer;
  119. internal List<TimerWrapper> timerWrapperList = new List<TimerWrapper>();
  120. private object timerWrapperListLock = new object();
  121. private EventHandler timerOnEnableEventHandler;
  122. private EventHandler timerOnDisableEventHandler;
  123. private StateMachine parentStateMachine;
  124. private int depth;
  125. private bool initialized;
  126. private object initalizeLock = new object();
  127. private string name;
  128. private StateNameKind logNameKind;
  129. private StateMachine mainStateMachine; // Refers to the main statemachine.
  130. /// <summary>
  131. /// Tells whether the object is disposed or not.
  132. /// </summary>
  133. protected internal bool disposed;
  134. /// <summary>
  135. /// The DebugLogger.
  136. /// </summary>
  137. internal protected IDebugLogger debugLogger;
  138. /// <summary>
  139. /// The LogCategory.
  140. /// </summary>
  141. internal protected object logCategory;
  142. #endregion
  143. #region Events
  144. /// <summary>
  145. /// Event that signals just before a state change will occur.
  146. /// </summary>
  147. public event EventHandler<StateChangedEventArgs> OnStateChange;
  148. /// <summary>
  149. /// Event that signals just after a state change has occured.
  150. /// </summary>
  151. public event EventHandler<StateChangedEventArgs> OnStateChanged;
  152. /// <summary>
  153. /// Even that is fired when the final state of a state machine is reached.
  154. /// </summary>
  155. public event EventHandler OnFinalStateEntered;
  156. #endregion
  157. #region Construction
  158. /// <summary>
  159. /// Constructor for the StateMachine class.
  160. /// </summary>
  161. internal StateMachine(string name, IDebugLogger debugLogger, object logCategory)
  162. {
  163. this.name = name;
  164. this.debugLogger = debugLogger;
  165. this.logCategory = logCategory;
  166. this.stateTypeContainer = new StateTypeContainer();
  167. stateLookup = new StateTransitionLookup(stateTypeContainer);
  168. timerOnDisableEventHandler = new EventHandler(timer_OnDisable);
  169. timerOnEnableEventHandler = new EventHandler(timer_OnEnable);
  170. }
  171. /// <summary>
  172. /// Destructor (finalizer). Stops the state machine if it has not already been done.
  173. /// </summary>
  174. ~StateMachine()
  175. {
  176. Dispose(false);
  177. }
  178. #endregion
  179. #region Public Methods
  180. /// <summary>
  181. /// Starts the state machine. This method should be called after the machine has been configured and
  182. /// equipped with at least one state factory.
  183. /// </summary>
  184. /// <exception cref="StateEngineException">Thrown if the engine is already started.</exception>
  185. public abstract void Start();
  186. /// <summary>
  187. /// Sends an event into the state machine.
  188. /// </summary>
  189. /// <param name="stateEngineEvent">Incoming event</param>
  190. public abstract void IncomingEvent(StateEngineEvent stateEngineEvent);
  191. /// <summary>
  192. /// Gets the pending envents from the parentStateMachine.
  193. /// </summary>
  194. /// <param name="eventType"></param>
  195. /// <returns>null or an IEnumberable</returns>
  196. public virtual IEnumerable<StateEngineEvent> GetPendingEventsOfType(object eventType)
  197. {
  198. return parentStateMachine != null ? parentStateMachine.GetPendingEventsOfType(eventType) : null;
  199. }
  200. /// <summary>
  201. /// DO NOT USE for any isfs based event!
  202. /// Removes all pending events that matches the specified event type. Comparison is made
  203. /// with the .Equals method.
  204. /// </summary>
  205. /// <param name="eventType"></param>
  206. public virtual void RemovePendingEventsOfType(object eventType)
  207. {
  208. if (parentStateMachine != null)
  209. parentStateMachine.RemovePendingEventsOfType(eventType);
  210. }
  211. /// <summary>
  212. /// Removes all pending event that matches the supplied predicate.
  213. /// </summary>
  214. /// <typeparam name="TComparisonObject">Type of the comparison object</typeparam>
  215. /// <param name="predicate">The predicate that is used to match the event.</param>
  216. /// <param name="comparisonObject">The comparison object that is used in the StateEngineEventPredicate.</param>
  217. public virtual void RemovePendingEvents<TComparisonObject>(StateEngineEventPredicate<TComparisonObject> predicate, TComparisonObject comparisonObject)
  218. {
  219. if (parentStateMachine != null)
  220. parentStateMachine.RemovePendingEvents(predicate, comparisonObject);
  221. }
  222. /// <summary>
  223. /// Gets all pending events that matches the supplied predicate
  224. /// </summary>
  225. /// <typeparam name="TComparisonObject">Type of the comparison object</typeparam>
  226. /// <param name="predicate">The predicate that is used to match the event.</param>
  227. /// <param name="comparisonObject">The comparison object that is used in the StateEngineEventPredicate.</param>
  228. /// <returns>enumberable of StateEngineEvents</returns>
  229. public virtual IEnumerable<StateEngineEvent> GetPendingEvents<TComparisonObject>(
  230. StateEngineEventPredicate<TComparisonObject> predicate, TComparisonObject comparisonObject)
  231. {
  232. return parentStateMachine != null ? parentStateMachine.GetPendingEvents(predicate, comparisonObject) : null;
  233. }
  234. /// <summary>
  235. /// Presents the class as a string.
  236. /// </summary>
  237. /// <returns></returns>
  238. public override string ToString()
  239. {
  240. return name;
  241. }
  242. #endregion
  243. #region State factory methods
  244. /// <summary>
  245. /// Clears the list of state factories.
  246. /// </summary>
  247. public void ClearStateFactories()
  248. {
  249. stateFactories.Clear();
  250. }
  251. /// <summary>
  252. /// Adds a custom state factory to the factory collection, so it can be used
  253. /// to create State objects.
  254. /// </summary>
  255. /// <param name="factory">The factory to add</param>
  256. public void AddStateFactory(IStateFactory factory)
  257. {
  258. stateFactories.AddFactory(factory);
  259. }
  260. #endregion
  261. #region Private Methods
  262. /// <summary>
  263. /// Performs the actual state transition.
  264. /// </summary>
  265. /// <param name="newState">
  266. /// The state that the machine shall enter.
  267. /// </param>
  268. /// <param name="entry">
  269. /// Parameters that defines the entry, like HistoryType and the source transition.
  270. /// </param>
  271. /// <param name="transition">Perform a transaction by assigning a transition object to this ref parameter.</param>
  272. private void PerformStateChange(State newState, Wayne.Lib.StateEngine.StateEntry entry, ref Transition transition)
  273. {
  274. // First, save the current state
  275. State oldState = currentState;
  276. CheckAndRemoveTimersForCurrentState();
  277. // Set which is the current state.
  278. currentState = newState;
  279. // Exit the old state
  280. if ((oldState != null) && oldState.Active)
  281. oldState.PerformExit();
  282. StateChangedEventArgs stateChangeEventArgs = new StateChangedEventArgs(oldState, newState, entry.SourceTransition);
  283. // Notify descendant classes and others intrested.
  284. if (OnStateChange != null)
  285. OnStateChange.Invoke(this, stateChangeEventArgs);
  286. // Enter the new state.
  287. currentState.PerformEnter(entry, ref transition);
  288. // Notify descendant classes and others intrested.
  289. if (OnStateChanged != null)
  290. OnStateChanged.Invoke(this, stateChangeEventArgs);
  291. }
  292. /// <summary>
  293. /// Returns a state object that corresponds to the string passed in.
  294. /// It first checks if the state object already is created and if it
  295. /// not finds the state, it asks the connected state factories to
  296. /// create it.
  297. /// </summary>
  298. /// <param name="stateFactoryName">
  299. /// Name of the state. This should correspond to a state that can
  300. /// be created by any of the state factories connected to the
  301. /// state machine.
  302. /// </param>
  303. /// <returns>
  304. /// A state object that corresponds to the state name.
  305. /// If the state can not be found, it will return null.
  306. /// </returns>
  307. private State GetState(string stateFactoryName)
  308. {
  309. State result;
  310. if (!createdStates.TryGetValue(stateFactoryName, out result))
  311. {
  312. createdStates.Add(stateFactoryName, result = CreateState(stateFactoryName));
  313. }
  314. return result;
  315. }
  316. /// <summary>
  317. /// Creates a state from the supplied state name.
  318. /// </summary>
  319. /// <param name="stateFactoryName"></param>
  320. /// <returns></returns>
  321. internal protected virtual State CreateState(string stateFactoryName)
  322. {
  323. State newState = stateFactories.CreateState(stateFactoryName, stateTypeContainer);
  324. if (newState == null && ParentStateMachine != null)
  325. newState = ParentStateMachine.stateFactories.CreateState(stateFactoryName, stateTypeContainer);
  326. if (newState == null && MainStateMachine != null)
  327. MainStateMachine.stateFactories.CreateState(stateFactoryName, stateTypeContainer);
  328. if (newState != null)
  329. {
  330. newState.WritableFactoryName = stateFactoryName;
  331. newState.SetParentStateMachine(this);
  332. newState.SetDebugLogger(debugLogger, logCategory);
  333. }
  334. return newState;
  335. }
  336. /// <summary>
  337. /// Forces the state machine to create all its states. It
  338. /// uses the state transition table to determine which objects are included in
  339. /// the machine.
  340. /// </summary>
  341. private void CreateStateObjects()
  342. {
  343. string[] stateFactoryNames = stateLookup.GetStateNameList(false);
  344. foreach (string stateFactoryName in stateFactoryNames)
  345. {
  346. State state = this.GetState(stateFactoryName);
  347. if (state != null)
  348. {
  349. InitialState tempInitState = state as InitialState;
  350. if (tempInitState != null)
  351. {
  352. initialState = tempInitState;
  353. }
  354. else
  355. {
  356. CompositeState compositeState = state as CompositeState;
  357. if (compositeState != null)
  358. {
  359. compositeState.Initialize();
  360. }
  361. }
  362. }
  363. else
  364. {
  365. throw new InvalidOperationException("Can not create state " + stateFactoryName);
  366. }
  367. }
  368. }
  369. #endregion
  370. #region Public Properties
  371. /// <summary>
  372. /// The state transition lookup object. Use to set up the state machine in code.
  373. /// </summary>
  374. public StateTransitionLookup StateTransitionLookup
  375. {
  376. get { return stateLookup; }
  377. }
  378. /// <summary>
  379. /// Indicates how many levels the state machine is from the bottom state machine. The first state machine has
  380. /// depth 0. States in a composite state to that machine has depth 1 and so on.
  381. /// </summary>
  382. public int Depth
  383. {
  384. get { return depth; }
  385. set { depth = value; }
  386. }
  387. /// <summary>
  388. /// Current state object.
  389. /// </summary>
  390. public State CurrentState
  391. {
  392. get { return currentState; }
  393. }
  394. /// <summary>
  395. /// Gets the current state by recursively entering composite states and returning the innermost state.
  396. /// </summary>
  397. public State CurrentStateRecursive
  398. {
  399. get
  400. {
  401. return GetStateRecursively(currentState);
  402. }
  403. }
  404. private State GetStateRecursively(State state)
  405. {
  406. if (state is CompositeState)
  407. {
  408. var compositeState = ((CompositeState)state);
  409. if (compositeState.StateMachine.CurrentState == null)
  410. return compositeState;
  411. else
  412. return GetStateRecursively(compositeState.StateMachine.CurrentState);
  413. }
  414. else
  415. {
  416. return state;
  417. }
  418. }
  419. /// <summary>
  420. /// List of the created states in the machine.
  421. /// </summary>
  422. public System.Collections.ObjectModel.ReadOnlyCollection<State> CreatedStates
  423. {
  424. get { return createdStates.Values.ToList().AsReadOnly(); }
  425. }
  426. /// <summary>
  427. /// Name of the state machine given when the state machine was created.
  428. /// </summary>
  429. public string Name
  430. {
  431. get { return name; }
  432. }
  433. /// <summary>
  434. /// Indicates that the state machine has been started.
  435. /// </summary>
  436. public abstract bool Started { get; }
  437. /// <summary>
  438. /// Initializes the state machine, creates all state objects.
  439. /// </summary>
  440. public void Initialize()
  441. {
  442. lock (initalizeLock)
  443. {
  444. if (!initialized)
  445. {
  446. //Force a creation of all states in the state machine.
  447. CreateStateObjects();
  448. if (initialState == null)
  449. throw new StateEngineException("Must set an initial state for the state machine! In " + name);
  450. initialized = true;
  451. }
  452. }
  453. }
  454. /// <summary>
  455. /// The kind of name to use for logging the state name.
  456. /// </summary>
  457. public StateNameKind LogNameKind
  458. {
  459. get { return MainStateMachine.logNameKind; }
  460. set { MainStateMachine.logNameKind = value; }
  461. }
  462. private StateMachine MainStateMachine
  463. {
  464. get
  465. {
  466. if (mainStateMachine == null)
  467. {
  468. if (parentStateMachine != null)
  469. {
  470. mainStateMachine = parentStateMachine;
  471. while (mainStateMachine.parentStateMachine != null)
  472. mainStateMachine = mainStateMachine.parentStateMachine;
  473. }
  474. else
  475. mainStateMachine = this;
  476. }
  477. return mainStateMachine;
  478. }
  479. }
  480. #endregion
  481. #region Internal Properties
  482. /// <summary>
  483. /// If the state machine is contained in a composite state, the state machine
  484. /// contains a reference to the state machine that owns the composite state.
  485. /// </summary>
  486. internal StateMachine ParentStateMachine
  487. {
  488. get { return parentStateMachine; }
  489. set { parentStateMachine = value; }
  490. }
  491. /// <summary>
  492. /// Indicates that all state objects have been created.
  493. /// </summary>
  494. internal bool Initialized
  495. {
  496. get
  497. {
  498. lock (initalizeLock)
  499. {
  500. return initialized;
  501. }
  502. }
  503. }
  504. /// <summary>
  505. /// Sets and merges the new state type container with the one that were there to begin with.
  506. /// </summary>
  507. /// <param name="newStateTypeContainer"></param>
  508. public void SetAndMergeTypeContainer(StateTypeContainer newStateTypeContainer)
  509. {
  510. newStateTypeContainer.Register(stateTypeContainer); //Copy the registered types from the current type container to the new one.
  511. stateTypeContainer = newStateTypeContainer;//Overwrite the old one.
  512. }
  513. #endregion
  514. #region Internal Methods
  515. /// <summary>
  516. /// Performs the entry of the initial state of the state machine.
  517. /// </summary>
  518. /// <param name="sourceTransition"></param>
  519. /// <param name="transition">If a transition should be performed, the transition reference is assigned to.</param>
  520. internal void EnterInitialState(Transition sourceTransition, ref Transition transition)
  521. {
  522. StateEntry stateEntry = null;
  523. if (sourceTransition == null)
  524. {
  525. stateEntry = new StateEntry(new Transition(null, BasicTransitionType.Init),
  526. this.initialState.FactoryName,
  527. HistoryType.None);
  528. }
  529. else
  530. {
  531. stateEntry = new StateEntry(sourceTransition, this.initialState.FactoryName, HistoryType.None);
  532. }
  533. PerformStateChange(this.initialState, stateEntry, ref transition);
  534. if (transition != null)
  535. this.HandleTransition(ref transition);
  536. }
  537. /// <summary>
  538. /// When the State machine is contained in a composite state, and the composite state is
  539. /// entered, this method is called , so the entry can be done.
  540. /// </summary>
  541. /// <param name="stateEntry">The entry containing information about with which history type to enter the state.</param>
  542. /// <param name="transition">If a transition should be performed, the transition reference is assigned to.</param>
  543. internal void EnterState(StateEntry stateEntry, ref Transition transition)
  544. {
  545. switch (stateEntry.HistoryType)
  546. {
  547. /////////////////////////////////
  548. case HistoryType.None:
  549. {
  550. EnterInitialState(stateEntry.SourceTransition, ref transition);
  551. break;
  552. }
  553. ////////////////////////////////
  554. case HistoryType.Shallow:
  555. {
  556. if (currentState != null)
  557. {
  558. var initEntry = new StateEntry(stateEntry.SourceTransition,
  559. initialState.FactoryName,
  560. HistoryType.None);
  561. PerformStateChange(currentState, initEntry, ref transition);
  562. }
  563. else
  564. EnterInitialState(stateEntry.SourceTransition, ref transition);
  565. break;
  566. }
  567. /////////////////////////////////
  568. case HistoryType.Deep:
  569. {
  570. if (currentState != null)
  571. {
  572. var InitEntry = new StateEntry(stateEntry.SourceTransition,
  573. initialState.FactoryName,
  574. HistoryType.Deep);
  575. PerformStateChange(currentState, InitEntry, ref transition);
  576. }
  577. else
  578. EnterInitialState(stateEntry.SourceTransition, ref transition);
  579. break;
  580. }
  581. /////////////////////////////////
  582. case HistoryType.Explicit:
  583. {
  584. var explicitTransition = stateEntry.SourceTransition;
  585. this.HandleTransition(ref explicitTransition);
  586. if (explicitTransition != null) //The handleTransition returned a new transition.
  587. transition = explicitTransition;
  588. break;
  589. }
  590. }
  591. }
  592. /// <summary>
  593. /// When the State machine is contained in a composite state, and the composite state is
  594. /// exited, this method is called, so the current state of the machine can be exited.
  595. /// </summary>
  596. internal void ExitState()
  597. {
  598. lock (this)
  599. {
  600. if (currentState != null)//Current state can be null in some rare startup cases.
  601. currentState.PerformExit();
  602. //Clear the timers when exiting.
  603. lock (timerWrapperListLock)
  604. {
  605. if ((debugLogger != null) && debugLogger.IsActive(DebugLogLevel.Maximized))
  606. debugLogger.Add("Disabling all TimerWrappers", DebugLogLevel.Maximized);
  607. var tempTimerWrapperList = new List<TimerWrapper>(timerWrapperList);
  608. foreach (var wrapper in tempTimerWrapperList)
  609. wrapper.Disable();
  610. }
  611. }
  612. }
  613. /// <summary>
  614. /// Handles events
  615. /// </summary>
  616. /// <param name="stateEngineEvent"></param>
  617. /// <param name="transition"></param>
  618. internal virtual void HandleEvent(StateEngineEvent stateEngineEvent, ref Transition transition)
  619. {
  620. currentState.IncomingEvent(stateEngineEvent, ref transition);
  621. if (transition != null)
  622. this.HandleTransition(ref transition);
  623. }
  624. /// <summary>
  625. /// Receives a transition from a state object. Looks up the transition and enters the correct next state.
  626. /// If this state machine is embedded in a composite state and the transition not resulted in a state change
  627. /// in this machine, the transition is passed on to the parent machine by changing the reference parameter to a new transition object.
  628. ///
  629. /// It is forbidden to transition from a final state in a state machine, so transitions made while we are
  630. /// in a final state is sent right to the state machine that contains the composite state that owns this
  631. /// machine.
  632. /// </summary>
  633. /// <param name="transition"></param>
  634. internal void HandleTransition(ref Transition transition)
  635. {
  636. var explicitTransition = transition as ExplicitTransition;
  637. bool transitionHandled;
  638. if (disposed)
  639. return;
  640. do
  641. {
  642. transitionHandled = false;
  643. //-------------------------------------
  644. //If it is NOT an explict transition
  645. if (explicitTransition == null)
  646. {
  647. //First, Check if this is a transition that has a configured target state
  648. //in this state machine.
  649. var entry = StateTransitionLookup.GetNextState(currentState.FactoryName, transition);
  650. if ((entry != null) && !(currentState is FinalState))
  651. {
  652. transitionHandled = true;
  653. transition = null;
  654. var St = this.GetState(entry.TargetStateFactoryName);
  655. if (St != null)
  656. PerformStateChange(St, entry, ref transition);
  657. }
  658. //If the current state is a final state, just drop the transition undhandled, and it will be
  659. //passed on to the parent state machine automatically through the ref parameter
  660. }
  661. //-------------------------------------
  662. //Explicit transition
  663. else
  664. {
  665. State nextState = null;
  666. //First search for the state pointed out by the target state, or at least a composite state that
  667. //contains the target state.
  668. foreach (var state in createdStates)
  669. {
  670. if (state.Value.LookupState(explicitTransition.TargetStateFactoryName))
  671. {
  672. nextState = state.Value;
  673. break;
  674. }
  675. }
  676. //If a state was found in this machine, enter the state.
  677. if (nextState != null)
  678. {
  679. var entry = new StateEntry(explicitTransition, nextState.FactoryName, HistoryType.Explicit);
  680. transition = null;
  681. transitionHandled = true;
  682. PerformStateChange(nextState, entry, ref transition);
  683. }
  684. //If the target state not is found, just drop the transition unhandled and it will be passed
  685. //on to the parent state machine automatically through the ref parameter
  686. }
  687. } while (transitionHandled && transition != null && !disposed);
  688. }
  689. /// <summary>
  690. /// Clears all pending events from the state machine.
  691. /// </summary>
  692. internal virtual void ClearPendingEvents()
  693. {
  694. if (parentStateMachine != null)
  695. parentStateMachine.ClearPendingEvents();
  696. }
  697. /// <summary>
  698. /// Fires the OnFinalStateEntered event.
  699. /// </summary>
  700. internal void FireFinalStateEntered()
  701. {
  702. if (OnFinalStateEntered != null)
  703. OnFinalStateEntered(this, EventArgs.Empty);
  704. }
  705. internal void SetDebugLogger(IDebugLogger debugLogger, object logCategory)
  706. {
  707. this.debugLogger = debugLogger;
  708. this.logCategory = logCategory;
  709. }
  710. #endregion
  711. #region IDisposable Members
  712. /// <summary>
  713. /// The private dispose method taking into account if it is disposed by the
  714. /// finalizer or through a explicit Dispose() call.
  715. /// </summary>
  716. /// <param name="disposing"></param>
  717. protected virtual void Dispose(bool disposing)
  718. {
  719. if (!disposed)
  720. {
  721. disposed = true;
  722. if ((debugLogger != null) && debugLogger.IsActive(logCategory))
  723. debugLogger.Add("--------- Stopping State machine (Dispose)---------", logCategory);
  724. if ((currentState != null) && currentState.Active)
  725. {
  726. currentState.PerformExit();
  727. currentState = null;
  728. }
  729. if (disposing)
  730. {
  731. //Dispose the timer wrappers
  732. lock (timerWrapperListLock)
  733. {
  734. List<TimerWrapper> tempTimerWrapperList = new List<TimerWrapper>(timerWrapperList);
  735. foreach (TimerWrapper timerWrapper in tempTimerWrapperList)
  736. {
  737. timerWrapper.Dispose();
  738. }
  739. timerWrapperList.Clear();
  740. }
  741. createdStates.Values.ForEach(x=>x.Dispose());
  742. createdStates.Clear();
  743. timerOnDisableEventHandler -= timer_OnDisable;
  744. timerOnEnableEventHandler -= timer_OnEnable;
  745. }
  746. }
  747. }
  748. /// <summary>
  749. /// Disposes resources.
  750. /// </summary>
  751. public void Dispose()
  752. {
  753. Dispose(true);
  754. GC.SuppressFinalize(this);
  755. }
  756. #endregion
  757. #region Timer methods
  758. /// <summary>
  759. /// Activate the supplied timer. This should be called from state object when they want a timer functionality.
  760. /// </summary>
  761. /// <param name="timer">The timer to activate</param>
  762. /// <see cref="Timer"/>
  763. public void ActivateTimer(Wayne.Lib.StateEngine.Timer timer)
  764. {
  765. timer.OnEnable += timerOnEnableEventHandler;
  766. timer.OnDisable += timerOnDisableEventHandler;
  767. timer.Enable();
  768. if ((debugLogger != null) && debugLogger.IsActive(DebugLogLevel.Maximized))
  769. debugLogger.Add("Activating timer for " + timer.ToString(), DebugLogLevel.Maximized);
  770. }
  771. /// <summary>
  772. /// A timer should be disabled. Get the timerwrapper for this stateengine timer and
  773. /// disable it if it exists.
  774. /// </summary>
  775. /// <param name="sender"></param>
  776. /// <param name="e"></param>
  777. void timer_OnDisable(object sender, EventArgs e)
  778. {
  779. Timer stateEngineTimer = (Timer)sender;
  780. if ((debugLogger != null) && debugLogger.IsActive(DebugLogLevel.Maximized))
  781. debugLogger.Add("Disabling StateEngineTimer " + stateEngineTimer.ToString(), DebugLogLevel.Maximized);
  782. lock (timerWrapperListLock)
  783. {
  784. // try to find a timer that is mapped to this state engine timer.
  785. TimerWrapper foundTimerWrapper = null;
  786. foreach (TimerWrapper wrapper in timerWrapperList)
  787. {
  788. if (wrapper.StateEngineTimer == stateEngineTimer)
  789. {
  790. foundTimerWrapper = wrapper;
  791. break;
  792. }
  793. }
  794. if (foundTimerWrapper != null)
  795. {
  796. foundTimerWrapper.StateEngineTimer = null;
  797. if (!TimerWrapperCaching)//Dispose the timer wrapper and remove it from the list.
  798. {
  799. foundTimerWrapper.Dispose();
  800. timerWrapperList.Remove(foundTimerWrapper);
  801. }
  802. //else //Old logic, just disable the timer, and cache it.
  803. //{
  804. // foundTimerWrapper.Disable();
  805. //}
  806. }
  807. }
  808. }
  809. /// <summary>
  810. /// A timer should be enabled, Get a TimerWrapper and attach the state engine timer.
  811. /// </summary>
  812. /// <param name="sender"></param>
  813. /// <param name="e"></param>
  814. void timer_OnEnable(object sender, EventArgs e)
  815. {
  816. Timer stateEngineTimer = (Timer)sender;
  817. if ((debugLogger != null) && (debugLogger.IsActive(DebugLogLevel.Maximized)))
  818. debugLogger.Add("Enabling StateEngineTimer for " + stateEngineTimer.ToString(), DebugLogLevel.Maximized);
  819. lock (timerWrapperListLock) //Lock here just in case. . .
  820. {
  821. TimerWrapper wrapper = GetTimerWrapper(stateEngineTimer);
  822. wrapper.Enable();
  823. }
  824. }
  825. /// <summary>
  826. /// Get a TimerWrapper that is 1)Already assigned to this state engine timer, 2) Available to use, 3)If none available, create a new wrapper.
  827. /// It does also assign the StateEngineTimer to the wrapper, so it is directly marked that it is taken.
  828. /// </summary>
  829. /// <param name="stateEngineTimer"></param>
  830. /// <returns></returns>
  831. private TimerWrapper GetTimerWrapper(Timer stateEngineTimer)
  832. {
  833. TimerWrapper wrapper = null;
  834. lock (timerWrapperListLock)
  835. {
  836. //First try to find a timer that already is mapped to this state engine timer.
  837. foreach (TimerWrapper tempWrapper in timerWrapperList)
  838. {
  839. if (tempWrapper.StateEngineTimer == stateEngineTimer)
  840. {
  841. wrapper = tempWrapper;
  842. break;
  843. }
  844. }
  845. //If not found, search for a timerwrapper that is free to use
  846. if (wrapper == null)
  847. {
  848. foreach (TimerWrapper tempWrapper in timerWrapperList)
  849. {
  850. if (tempWrapper.StateEngineTimer == null)
  851. {
  852. wrapper = tempWrapper;
  853. wrapper.StateEngineTimer = stateEngineTimer;
  854. break;
  855. }
  856. }
  857. }
  858. //Otherwise, create a new wrapper and add it to the list.
  859. if (wrapper == null)
  860. {
  861. wrapper = new TimerWrapper(TimerFired);
  862. wrapper.StateEngineTimer = stateEngineTimer;
  863. timerWrapperList.Add(wrapper);
  864. }
  865. }
  866. return wrapper;
  867. }
  868. /// <summary>
  869. /// One of the timers in the timer list has fired. Create a timer event and enqueue it.
  870. /// </summary>
  871. /// <param name="state"></param>
  872. void TimerFired(object state)
  873. {
  874. TimerWrapper timerWrapper = (TimerWrapper)state;
  875. StateEngineEvent stateEngineEvent = null;
  876. lock (timerWrapperListLock)
  877. {
  878. Timer stateEngineTimer = timerWrapper.StateEngineTimer;
  879. if (stateEngineTimer != null)
  880. {
  881. if ((debugLogger != null) && debugLogger.IsActive(DebugLogLevel.Maximized))
  882. debugLogger.Add("StateEngineTimer Fired " + stateEngineTimer.ToString(), DebugLogLevel.Maximized);
  883. //If this is a one time timer, it should be removed from the timer list, and be disabled.
  884. if (!stateEngineTimer.IsPeriodic)
  885. {
  886. stateEngineTimer.Disable();
  887. }
  888. stateEngineEvent = new TimerEvent(stateEngineTimer.UserToken, stateEngineTimer.EventType);
  889. }
  890. }
  891. if (stateEngineEvent != null)
  892. IncomingEvent(stateEngineEvent); //We want to fire the event outside the lock to see so we don't happen to deadlock with other locks in the state machine.
  893. }
  894. /// <summary>
  895. /// Removes the timers that is owned by the current state, and that is specified to be cleared at exit.
  896. /// </summary>
  897. private void CheckAndRemoveTimersForCurrentState()
  898. {
  899. //Check if there are any timers that should be removed before leaving the state.
  900. lock (timerWrapperListLock)
  901. {
  902. List<TimerWrapper> tempTimerWrapperList = new List<TimerWrapper>(timerWrapperList); //Create a copy of the timer wrapper list to iterate since it will modify.
  903. foreach (TimerWrapper timerWrapper in tempTimerWrapperList)
  904. {
  905. if (timerWrapper.StateEngineTimer != null)
  906. {
  907. if (timerWrapper.StateEngineTimer.OwnerState == currentState)
  908. {
  909. if (timerWrapper.StateEngineTimer.ClearAtStateExit)
  910. {
  911. if ((debugLogger != null) && debugLogger.IsActive(DebugLogLevel.Maximized))
  912. debugLogger.Add("!IsPeriodic: Disabling timer because of state change " + timerWrapper.StateEngineTimer.ToString(), DebugLogLevel.Maximized);
  913. timerWrapper.StateEngineTimer.Disable();//This will trigger the wrapper to remove its StateEngineTimer.
  914. }
  915. }
  916. }
  917. }
  918. }
  919. }
  920. #endregion
  921. #region Static Methods
  922. /// <summary>
  923. /// Creates and returns StateMachine object. This method creates Threaded Statemachine. To create other implementations,
  924. /// use the <c>Create(StateMachineType stateMachineType, string name)</c> method instead.
  925. /// </summary>
  926. /// <param name="name">Name of the state machine.</param>
  927. /// <param name="debugLogger">The DebugLogger to use.</param>
  928. /// <param name="logCategory">The log category.</param>
  929. /// <returns>A statemachine object</returns>
  930. public static StateMachine Create(string name, IDebugLogger debugLogger, object logCategory)
  931. {
  932. return Create(name, StateMachineType.Threaded, debugLogger, logCategory);
  933. }
  934. /// <summary>
  935. /// Creates and returns StateMachine object. The state machine type determines wich implementation should be used.
  936. /// </summary>
  937. /// <param name="name">Name of the state machine.</param>
  938. /// <param name="stateMachineType">Type of state machine implementation that should be created.</param>
  939. /// <param name="debugLogger">The DebugLogger to use.</param>
  940. /// <param name="logCategory">The log category.</param>
  941. /// <returns></returns>
  942. public static StateMachine Create(string name, StateMachineType stateMachineType, IDebugLogger debugLogger, object logCategory)
  943. {
  944. switch (stateMachineType)
  945. {
  946. case StateMachineType.Threaded: return new ThreadedRootStateMachine(name, debugLogger, logCategory);
  947. case StateMachineType.Synchronous: return new SynchronousRootStateMachine(name, debugLogger, logCategory);
  948. default: throw new NotImplementedException("This statemachine type is not yet implemented.");
  949. }
  950. }
  951. #endregion
  952. }
  953. }