State.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  1. using System;
  2. using System.Globalization;
  3. using Wayne.Lib.Log;
  4. namespace Wayne.Lib.StateEngine
  5. {
  6. /// <summary>
  7. /// History type defines the way that a composite state is entered.
  8. /// </summary>
  9. public enum HistoryType
  10. {
  11. #region Fields
  12. /// <summary>
  13. /// Only the initial state is entered. No history is recalled
  14. /// </summary>
  15. None,
  16. /// <summary>
  17. /// If the composite has been active before, the state that was
  18. /// active last is entered. Shallow means that entering the
  19. /// recalled last state but when entering that state, it is done with
  20. /// no history.
  21. /// </summary>
  22. Shallow,
  23. /// <summary>
  24. /// If a composite state has been active before, the state that was active
  25. /// last is entered, Deep means that if the recalled state is a composite
  26. /// it will also be entered with deep history.
  27. /// </summary>
  28. Deep,
  29. /// <summary>
  30. /// Explicit history type is *only* used when issuing explicit transitions. If
  31. /// a state machine is configured with this history type, an error will be thrown.
  32. /// </summary>
  33. Explicit
  34. #endregion
  35. }
  36. // StateType for future use.
  37. /// <summary>
  38. /// The state types as an enumeration. This can be used in a future design tool.
  39. /// </summary>
  40. public enum StateType
  41. {
  42. #region Fields
  43. /// <summary>
  44. /// Intial state
  45. /// </summary>
  46. InitialState,
  47. /// <summary>
  48. /// Pseudo state
  49. /// </summary>
  50. PseudoState,
  51. /// <summary>
  52. /// Ordinary state
  53. /// </summary>
  54. State,
  55. /// <summary>
  56. /// Composite state
  57. /// </summary>
  58. CompositeState,
  59. /// <summary>
  60. /// Final state
  61. /// </summary>
  62. FinalState
  63. #endregion
  64. }
  65. /// <summary>
  66. /// State is the base state of all states in the state machine.
  67. /// </summary>
  68. abstract public class State : IDisposable
  69. {
  70. #region Fields
  71. private Wayne.Lib.StateEngine.StateMachine parentStateMachine;
  72. private string createdByFactory = "";
  73. private bool active;
  74. private CompositeState parentState;
  75. private IDebugLogger debugLogger;
  76. private object logCategory;
  77. private string instanceName;
  78. private string factoryName;
  79. #endregion
  80. #region Methods
  81. /// <summary>
  82. /// Enter is called when the state machine enters the state. Override this method to be able to
  83. /// run code at the state entry. If a transition should be performed, create a transition object
  84. /// and return it in the transition out property.
  85. /// </summary>
  86. /// <param name="stateEntry">Information about the entry of the state.</param>
  87. /// <param name="transition">Out parameter, that should be set to either the reference to a transition object or null.</param>
  88. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference", MessageId = "1#")]
  89. protected virtual void Enter(StateEntry stateEntry, ref Transition transition)
  90. {
  91. }
  92. /// <summary>
  93. /// Override this method to implement code that should be run at state exit.
  94. /// </summary>
  95. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters", MessageId = "Wayne.Lib.StateEngine.State.DebugLog(System.String)")]
  96. protected virtual void Exit()
  97. {
  98. }
  99. /// <summary>
  100. /// Override to receive incoming events. If the event is handled, the
  101. /// application must set the event.Handled = true.
  102. /// </summary>
  103. /// <param name="stateEngineEvent">The event object that should be handled.</param>
  104. /// <param name="transition">Out parameter that should be set to either the reference to a transition object or null.</param>
  105. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference", MessageId = "1#")]
  106. protected virtual void HandleEvent(StateEngineEvent stateEngineEvent, ref Transition transition)
  107. {
  108. }
  109. /// <summary>
  110. /// Activates the supplied timer.
  111. /// </summary>
  112. /// <param name="timer">The timer to activate.</param>
  113. /// <see cref="Timer"/>
  114. protected virtual void ActivateTimer(Timer timer)
  115. {
  116. if (parentStateMachine != null)
  117. parentStateMachine.ActivateTimer(timer);
  118. }
  119. /// <summary>
  120. /// Disposes the resources owned by the state object.
  121. /// </summary>
  122. /// <param name="disposing"></param>
  123. protected virtual void Dispose(bool disposing)
  124. {
  125. //Nothing in an ordinary state.
  126. }
  127. /// <summary>
  128. /// Clears all events waiting in the event queues.
  129. /// </summary>
  130. protected void ClearPendingEvents()
  131. {
  132. this.parentStateMachine.ClearPendingEvents();
  133. }
  134. /// <summary>
  135. /// Clears all the events in the resend queue that matches the eventType.
  136. /// </summary>
  137. /// <param name="eventType"></param>
  138. protected void RemovePendingEventsOfType(object eventType)
  139. {
  140. this.parentStateMachine.RemovePendingEventsOfType(eventType);
  141. }
  142. /// <summary>
  143. /// Removes all pending event that matches the supplied predicate.
  144. /// </summary>
  145. /// <typeparam name="TComparisonObject">Type of the comparison object</typeparam>
  146. /// <param name="predicate">The predicate that is used to match the event.</param>
  147. /// <param name="comparisonObject">The comparison object that is used in the StateEngineEventPredicate.</param>
  148. protected void RemovePendingEvents<TComparisonObject>(StateEngineEventPredicate<TComparisonObject> predicate, TComparisonObject comparisonObject)
  149. {
  150. this.ParentStateMachine.RemovePendingEvents(predicate, comparisonObject);
  151. }
  152. /// <summary>
  153. /// Disposes all the owned resources in the state.
  154. /// </summary>
  155. public void Dispose()
  156. {
  157. Dispose(true);
  158. }
  159. #endregion
  160. #region Internal Methods
  161. /// <summary>
  162. /// Incoming event is called from the state machine when an event should be handled.
  163. /// </summary>
  164. /// <param name="stateEngineEvent"></param>
  165. /// <param name="transition">Perform a transition by assigning a transition object to this reference parameter.</param>
  166. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
  167. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters", MessageId = "Wayne.Lib.StateEngine.State.DebugLog(System.String)")]
  168. internal virtual void IncomingEvent(StateEngineEvent stateEngineEvent, ref Transition transition)
  169. {
  170. try
  171. {
  172. if (!(this is CompositeState))
  173. {
  174. if ((debugLogger != null) && (debugLogger.IsActive(logCategory)))
  175. debugLogger.Add(string.Format(System.Globalization.CultureInfo.InvariantCulture, " [{0}] HandleEvent: {1}", this.LogName, stateEngineEvent), logCategory);
  176. }
  177. if (!stateEngineEvent.Handled)
  178. {
  179. //Call the HandleEvent method of the state
  180. HandleEvent(stateEngineEvent, ref transition);
  181. }
  182. //If a transition was issued, equip it with the event as source event.
  183. if (transition != null)
  184. transition.WritableSourceEvent = stateEngineEvent;
  185. }
  186. catch (Exception exception)
  187. {
  188. if ((debugLogger != null) && (debugLogger.IsActive(logCategory)))
  189. {
  190. System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();
  191. stringBuilder.Append("EXCEPTION IN HandleEvent (");
  192. stringBuilder.Append(this.LogName);
  193. stringBuilder.Append(")\r\n");
  194. stringBuilder.Append(exception.ToString());
  195. debugLogger.Add(stringBuilder, logCategory);
  196. }
  197. transition = new ExceptionTransition(this, BasicTransitionType.Error, exception);
  198. }
  199. #if WindowsCE
  200. catch
  201. {
  202. if ((debugLogger != null) && (debugLogger.IsActive(logCategory)))
  203. {
  204. debugLogger.Add("Unknown exception in HandleEvent (" + this.LogName + ")");
  205. }
  206. transition = new Transition(this, BasicTransitionType.Error);
  207. }
  208. #endif
  209. }
  210. /// <summary>
  211. /// Called from the state machine when the state is entered. It is up to the state to
  212. /// call the appropriate virtual Enter methods. If a transition should be performed it
  213. /// is returned in the Transition ref parameter.
  214. /// </summary>
  215. /// <param name="stateEntry">State entry object containing information about the state entry.</param>
  216. /// <param name="transition">Perform a transition by assigning a transition object to this ref parameter.</param>
  217. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
  218. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters", MessageId = "Wayne.Lib.StateEngine.State.DebugLog(System.String)")]
  219. internal virtual void PerformEnter(StateEntry stateEntry, ref Transition transition)
  220. {
  221. active = true;
  222. try
  223. {
  224. if (!(this is CompositeState))
  225. if ((debugLogger != null) && (debugLogger.IsActive(logCategory)))
  226. debugLogger.Add(string.Format(System.Globalization.CultureInfo.InvariantCulture, " [{0}] Enter: Transition={1}", this.LogName, stateEntry.SourceTransition.Name), logCategory);
  227. //Call the enter method of the state.
  228. Enter(stateEntry, ref transition);
  229. //If a transition was issued, equip it with the event as source event.
  230. if (transition != null)
  231. if ((stateEntry != null) && (stateEntry.SourceTransition != null))
  232. transition.WritableSourceEvent = stateEntry.SourceTransition.SourceEvent;
  233. }
  234. catch (Exception exception)
  235. {
  236. if ((debugLogger != null) && (debugLogger.IsActive(logCategory)))
  237. {
  238. System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();
  239. stringBuilder.Append("EXCEPTION IN Enter (");
  240. stringBuilder.Append(this.LogName);
  241. stringBuilder.Append(")\r\n");
  242. stringBuilder.Append(exception.ToString());
  243. debugLogger.Add(stringBuilder.ToString(), logCategory);
  244. }
  245. transition = new ExceptionTransition(this, BasicTransitionType.Error, exception);
  246. }
  247. #if WindowsCE
  248. catch
  249. {
  250. if ((debugLogger != null) && (debugLogger.IsActive(logCategory)))
  251. debugLogger.Add("Unknown exception in Enter (" + this.LogName + ")");
  252. transition = new Transition(this, BasicTransitionType.Error);
  253. }
  254. #endif
  255. }
  256. /// <summary>
  257. /// This method is called by the state machine when the state should be exited. It contains the error handling
  258. /// logic and logging of the exit.
  259. /// </summary>
  260. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
  261. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters", MessageId = "Wayne.Lib.StateEngine.State.DebugLog(System.String)")]
  262. internal virtual void PerformExit()
  263. {
  264. active = false;
  265. try
  266. {
  267. Exit();
  268. }
  269. catch (Exception exception)
  270. {
  271. if ((debugLogger != null) && (debugLogger.IsActive(logCategory)))
  272. {
  273. System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();
  274. stringBuilder.Append("EXCEPTION IN Exit (");
  275. stringBuilder.Append(this.LogName);
  276. stringBuilder.Append(")\r\n");
  277. stringBuilder.Append(exception.ToString());
  278. debugLogger.Add(stringBuilder, logCategory);
  279. }
  280. }
  281. #if WindowsCE
  282. catch
  283. {
  284. if ((debugLogger != null) && (debugLogger.IsActive(logCategory)))
  285. debugLogger.Add("Unknown exception in Exit (" + this.LogName + ")");
  286. }
  287. #endif
  288. }
  289. /// <summary>
  290. /// This function is used to locate a specific state in the state machine.
  291. /// In the state class it is simply compared to the state Factory Name. More complex comparisons
  292. /// is done in composite states.
  293. /// </summary>
  294. /// <param name="stateFactoryName">The factory name of the state that should be looked up.</param>
  295. /// <returns>True if the state is or contains a state with this name.</returns>
  296. internal virtual bool LookupState(string stateFactoryName)
  297. {
  298. return (stateFactoryName == this.FactoryName);
  299. }
  300. internal void AssignParentState(CompositeState parentState)
  301. {
  302. this.parentState = parentState;
  303. }
  304. #endregion
  305. #region Properties
  306. /// <summary>
  307. /// The factory name of the state (the full class name).
  308. /// </summary>
  309. public string FactoryName
  310. {
  311. get
  312. {
  313. return factoryName;
  314. }
  315. }
  316. /// <summary>
  317. /// Factory name of the class assigned after factory created the state.
  318. /// </summary>
  319. internal string WritableFactoryName
  320. {
  321. get { return factoryName; }
  322. set { this.factoryName = value; }
  323. }
  324. /// <summary>
  325. /// The name of this particular instance of this state (the hierarchical name of the state,
  326. /// starting with the name of the statemachine, through all parent composite states up to this state).
  327. /// </summary>
  328. public string InstanceName
  329. {
  330. get
  331. {
  332. if (instanceName != null)
  333. {
  334. return instanceName;
  335. }
  336. //I have a parent state - use that and append my name
  337. if (parentState != null)
  338. {
  339. return instanceName = string.Format("{0}.{1}", parentState.InstanceName, this.Name);
  340. }
  341. //I'm on the root - just use state machine name and append my name
  342. return instanceName = string.Format("{0}.{1}", ParentStateMachine.Name, Name);
  343. }
  344. }
  345. public virtual string Name
  346. {
  347. get { return this.GetType().Name; }
  348. }
  349. /// <summary>
  350. /// The name of the state used for logging.
  351. /// </summary>
  352. public string LogName
  353. {
  354. get
  355. {
  356. if (parentStateMachine != null)
  357. {
  358. switch (parentStateMachine.LogNameKind)
  359. {
  360. case StateNameKind.FactoryName: return FactoryName;
  361. case StateNameKind.InstanceName: return InstanceName;
  362. }
  363. }
  364. return FactoryName;
  365. }
  366. }
  367. /// <summary>
  368. /// Name of the state factory that created the state object.
  369. /// </summary>
  370. public string CreatedByFactory
  371. {
  372. get
  373. {
  374. return createdByFactory;
  375. }
  376. set
  377. {
  378. createdByFactory = value;
  379. }
  380. }
  381. /// <summary>
  382. /// Indicates that this is the current active state of the machine.
  383. /// </summary>
  384. public bool Active
  385. {
  386. get
  387. {
  388. return active;
  389. }
  390. }
  391. /// <summary>
  392. /// Provides a reference to the composite state this state is contained in. If it is in the root of the
  393. /// state machine, it will be null.
  394. /// </summary>
  395. public CompositeState ParentState
  396. {
  397. get { return parentState; }
  398. }
  399. /// <summary>
  400. /// The StateType.
  401. /// </summary>
  402. public StateType StateType
  403. {
  404. get
  405. {
  406. if (this is InitialState)
  407. return StateType.InitialState;
  408. else if (this is FinalState)
  409. return StateType.FinalState;
  410. else if (this is PseudoState)
  411. return StateType.PseudoState;
  412. else if (this is CompositeState)
  413. return StateType.CompositeState;
  414. return StateType.State;
  415. }
  416. }
  417. /// <summary>
  418. /// The parent state machine for the state.
  419. /// </summary>
  420. public StateMachine ParentStateMachine
  421. {
  422. get { return parentStateMachine; }
  423. }
  424. /// <summary>
  425. /// An additional text that shows up in the visualizer, that for instance can
  426. /// be used to point out application specific states.
  427. /// </summary>
  428. public virtual string ApplicationText
  429. {
  430. get;
  431. set;
  432. }
  433. #endregion
  434. #region Internal properties
  435. /// <summary>
  436. /// Set the parent state machine for the state.
  437. /// </summary>
  438. internal virtual void SetParentStateMachine(StateMachine parentStateMachine)
  439. {
  440. this.parentStateMachine = parentStateMachine;
  441. }
  442. /// <summary>
  443. /// Sets the debug logger.
  444. /// </summary>
  445. /// <param name="debugLogger"></param>
  446. /// <param name="logCategory"></param>
  447. internal virtual void SetDebugLogger(IDebugLogger debugLogger, object logCategory)
  448. {
  449. this.debugLogger = debugLogger;
  450. this.logCategory = logCategory;
  451. }
  452. #endregion
  453. /// <summary>
  454. /// Uses the debug logger passed in to the StateMachine upon creation to
  455. /// log the supplied logging if the logger is active.
  456. /// </summary>
  457. /// <param name="format"></param>
  458. /// <param name="params"></param>
  459. protected void DebugLog(string format, params object[] @params)
  460. {
  461. try
  462. {
  463. if (debugLogger.IsActive())
  464. {
  465. var message = @params != null && @params.Length > 0 ?
  466. string.Format(CultureInfo.InvariantCulture, format, @params) :
  467. format;
  468. debugLogger.Add(message);
  469. }
  470. }
  471. catch (FormatException)
  472. {
  473. if (debugLogger.IsActive())
  474. debugLogger.Add("LOGERROR: Could not format string: " + format);
  475. }
  476. }
  477. /// <summary>
  478. /// Uses the debug logger passed in to the StateMachine upon creation to
  479. /// log the supplied logging if the logger is active.
  480. /// </summary>
  481. /// <param name="format"></param>
  482. /// <param name="params"></param>
  483. protected void DebugLogDetailed(string format, params object[] @params)
  484. {
  485. try
  486. {
  487. if (debugLogger.IsActive(DebugLogLevel.Detailed))
  488. {
  489. var message = @params != null && @params.Length > 0 ?
  490. string.Format(CultureInfo.InvariantCulture, format, @params) :
  491. format;
  492. debugLogger.Add(message, DebugLogLevel.Detailed);
  493. }
  494. }
  495. catch (FormatException)
  496. {
  497. if (debugLogger.IsActive(DebugLogLevel.Detailed))
  498. debugLogger.Add("LOGERROR: Could not format string: " + format, DebugLogLevel.Detailed);
  499. }
  500. }
  501. /// <summary>
  502. /// Uses the debug logger passed in to the StateMachine upon creation to
  503. /// log the supplied logging if the logger is active.
  504. /// </summary>
  505. /// <param name="format"></param>
  506. /// <param name="params"></param>
  507. protected void DebugLogMaximized(string format, params object[] @params)
  508. {
  509. try
  510. {
  511. if (debugLogger.IsActive(DebugLogLevel.Detailed))
  512. {
  513. var message = @params != null && @params.Length > 0 ?
  514. string.Format(CultureInfo.InvariantCulture, format, @params) :
  515. format;
  516. debugLogger.Add(message, DebugLogLevel.Maximized);
  517. }
  518. }
  519. catch (FormatException)
  520. {
  521. if (debugLogger.IsActive(DebugLogLevel.Detailed))
  522. debugLogger.Add("LOGERROR: Could not format string: " + format, DebugLogLevel.Maximized);
  523. }
  524. }
  525. }
  526. }