StateController.h
Go to the documentation of this file.
1 /*
2 * This file is part of ArmarX.
3 *
4 * Copyright (C) 2011-2016, High Performance Humanoid Technologies (H2T), Karlsruhe Institute of Technology (KIT), all rights reserved.
5 *
6 * ArmarX is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License version 2 as
8 * published by the Free Software Foundation.
9 *
10 * ArmarX is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 *
18 * @package ArmarX::statechart
19 * @author Mirko Waechter ( mirko.waechter at kit dot edu)
20 * @date 2012
21 * @copyright http://www.gnu.org/licenses/gpl-2.0.txt
22 * GNU General Public License
23 */
24 
25 #pragma once
26 
27 #include "StateBase.h"
28 
29 #include <functional>
30 #include <memory>
31 
32 namespace armarx
33 {
34  class StateController;
36  template <typename Type>
37  class RunningTask;
38 }
39 
40 namespace armarx::Profiler
41 {
42  class Profiler;
43  using ProfilerPtr = std::shared_ptr<Profiler>;
44  using ProfilerSet = std::set<ProfilerPtr>;
45 }
46 
47 namespace armarx
48 {
49  /**
50  *\class StateController
51  *\ingroup StatechartGrp
52  * The StateController class processes events and controls the
53  * statechart flow.
54  */
56  virtual public StateBase
57  {
58  public:
59  using transitionFunction = std::function<void(StateController* state, const StateIceBasePtr& nextState, const StateIceBasePtr& previousState)>;
60  using TransitionFunctionMap = std::map<std::string, transitionFunction >;
61 
64  ~StateController() override;
65 
66  bool isFinished() const;
67  /**
68  * @brief waitForStateToFinish waits until this thread has finished
69  * (i.e. a FinalSubState has been reached).<br/>
70  *
71  * This function can only be called in a toplevelstate (a state with
72  * no parent state).
73  *
74  * @param timeOutMs
75  * @see isFinished()
76  */
77  void waitForStateToFinish(int timeoutMs = -1) const;
78 
79 
80  /**
81  * @brief disableRunFunction sets useRunFunction to false and waits
82  * (blocking) for the current StateBase::run() function to complete.
83  *
84  * @note This function needs to be called <b>before</b> the destructor of the
85  * state is called. If not called before destructor, the StateBase::run()
86  * function might cause a segfault.
87  */
88  void disableRunFunction();
89 
90  /**
91  * @brief isRunningTaskStopped checks whether the RunningTask, that
92  * executes run() is requested to stop. Check this function periodically in
93  * run()
94  * @return status of runningtask
95  */
96  bool isRunningTaskStopped() const;
97 
98  /**
99  * @brief Checks whether the run() function has already finished
100  * @return true if finished
101  */
102  bool isRunningTaskFinished() const;
103 
104  /**
105  * @brief Waits until the run-function has finished. This might be useful to do in onBreak() or onEnter()
106  * @see onEnter(), onBreak(), onRun()
107  */
108  void waitForRunningTaskToFinish() const;
109 
110  /**
111  * @brief Disables the reporting to profilers for this states during state visits.
112  */
113  void disableStateReporting(bool disable = true);
114 
115  void addTransitionFunction(const TransitionIceBase& t, transitionFunction function);
116  std::string getTransitionID(const TransitionIceBase& t) const;
117  std::string getTransitionID(const std::string& eventName, const std::string sourceStateName) const;
118  bool findTransition(const std::string& eventName, const std::string sourceStateName, TransitionIceBase& transition);
119 
120  /*! \brief Function to set the statemachine in the first state and call OnEnter().
121  *
122  * Should only be called for the outer most state(machine).
123  * All initial substates of this state and of it's substates are also entered.
124  * @param inputparameters Dictionary of parameters that should be mapped into the
125  * input parameters of this state. Uses '*'=>'*' mapping.
126  */
127  void enter(const StringVariantContainerBaseMap& tempInputParameters = StringVariantContainerBaseMap());
128 
129 
130  /**
131  * \brief Called by StateControllerprocessEvent()-function or parentstate. Must NOT
132  * be called by user.
133  *
134  * Calls OnEnter() in this hierarchylevel and of every initialstate of all sub levels.
135  */
136  virtual void _baseOnEnter() ;
137 
138  virtual void _startRun();
139  virtual void _baseRun();
140 
141  /*! \brief Called by StateController::processEvent()-function or parentstate. Must NOT
142  be called by user.
143 
144  Calls OnExit() in this hierarchylevel and all sub levels.
145  @relates baseOnExit()
146  */
147  virtual void _baseOnExit() ;
148 
149  /*! \brief Called by StateControllerprocessEvent()-function or parentstate. Must NOT be called by user.
150 
151  Calls OnBreak() in this hierarchylevel and all sub levels.
152  */
153  virtual bool _baseOnBreak(const EventPtr evt);
154 
155 
156  /**
157  * @brief addProfilerRecursive recursively adds a new armarx::Profiler::Profiler object as armarx::StateController::localProfiler(the default one does not do anything at all).
158  *
159  * \p recursiveLevels determins how many levels deep this new profiler object should be set:
160  *
161  * \li == -1: all reachable substates
162  * \li == 0: only current state
163  * \li > 0: current state + \p recursiveLevels deep)
164  *
165  * This is automtically set in armarx::StatechartContext::setToplevelState() based on statechart properties.
166  *
167  * @param profiler profiler instance to use in the state for calling armarx::Profiler::Profiler methods
168  * @param recursiveLevels how many levels deep the profiler should be set
169  */
170  void addProfilerRecursive(Profiler::ProfilerPtr profiler, int recursiveLevels = 0);
171  void removeProfilerRecursive(Profiler::ProfilerPtr profiler, int recursiveLevels = 0);
172 
173  struct Impl;
174  std::unique_ptr<Impl> cimpl;
175 
176  /**
177  * @brief Getter function that automatically casts the parentState
178  * member of StateBase into StateControllerPtr. @throw LocalException
179  * if parent state could not be cas @return Pointer to the parent state
180  */
182 
183  virtual bool __breakActiveSubstate(const EventPtr event);
184 
185  /*! \brief Function that gets called, when a state enters a FinalSubstate.
186  Virtual function, so that RemoteStateWrapper can override it.
187  */
188  virtual void __finalize(const EventPtr event);
189 
190  /*! \brief Function that gets called, when a state enters a FinalSubstate.
191  Virtual function, so that RemoteStateWrapper can override it.
192  */
193  virtual void __substatesFinished(const EventPtr ev);
194 
195  virtual void __enqueueEvent(const EventPtr event);
196 
197  /**
198  * @brief This function is implemented in StateUtil and removes all conditions
199  * that have been installed in onEnter() or run(). It is called after onExit()
200  */
201  virtual void _removeInstalledConditions() {}
202 
203 
204  /** \brief Before:Function to get the unbreakable-buffer status of all
205  parent state - recursively. * now: checks the flag for the buffer, that
206  gets set externally @return Returns true if no parent has any events in
207  the unbreakable buffer, false otherwise.
208  */
209  virtual bool __getUnbreakableBufferStati() const;
210 
211  /*! \brief Main function to control the statemachine/state.
212 
213  Determines with Parameter \c event, the active state and the
214  transitiontable, which transition to choose.<br/> If no transition
215  is found, an eUnexpectedEvent-exception is thrown.
216  */
217  virtual void __processEvent(const EventPtr event, bool buffered = false);
218 
219  /**
220  * @brief Apply the mappings during a transitions. The order is parent's local,
221  * parent's output and then next state's input.
222  * @param srcState
223  * @param t Transition that is currently executed
224  * @param event Event that led to the transition
225  */
226  bool __applyMappings(const StateControllerPtr& srcState, const TransitionIceBase& t, const EventPtr& event, TransitionError& error);
227  void __printTransitionError(const TransitionError& transitionError, const EventPtr& event) const;
228 
229 
230  bool __findValidTransition(const EventPtr& event, const StateIceBasePtr& sourceState, TransitionIceBase& resultTransition, TransitionError& error) const;
231  TransitionError __validateTransition(const TransitionIceBase& transition, const EventPtr event, const StateIceBasePtr& sourceState, const StateIceBasePtr& destinationState) const;
232 
233  virtual unsigned int __getUnbreakableBufferSize() const;
234 
235  /*! This virtual function notifies all substates that an event has been
236  * buffered due to unbreakable states and that they must not process any
237  * further events when they have reached a breakable state.
238  **/
239  virtual void __notifyEventBufferedDueToUnbreakableState(bool eventBuffered = true);
240 
241  /*! \brief Processes buffered events, that could not be processed immediately due to unbreakable substates.
242 
243  Gets called after a transition from a unbreakable substate to a breakable substate after execution of OnEnter() of the breakable state.<br/>
244  It is not called yet, when a transition occurs between 2 unbreakable states.<br/>
245  The calling substate can be of any level below this state in the hierarchy.<br/>
246  */
247  virtual void __processBufferedEvents();
248 
249  void __waitForRemoteStates() const;
250 
251  bool __checkExistenceOfTransition(const TransitionIceBase& transition);
252 
253  friend class State;
254  friend class StateUtility;
255  template <class EventType, class StateType> friend class FinalStateBase;
256  template <typename ContextType> friend class RemoteStateOfferer;
257  friend class RemoteState;
258  friend class DynamicRemoteState;
260  friend class StatechartManager;
261  friend class StatechartContext;
262  };
263 }
armarx::StateController::__validateTransition
TransitionError __validateTransition(const TransitionIceBase &transition, const EventPtr event, const StateIceBasePtr &sourceState, const StateIceBasePtr &destinationState) const
Definition: StateController.cpp:461
armarx::StateController::__processEvent
virtual void __processEvent(const EventPtr event, bool buffered=false)
Main function to control the statemachine/state.
Definition: StateController.cpp:299
armarx::StateController::__getParentState
StateControllerPtr __getParentState() const
Getter function that automatically casts the parentState member of StateBase into StateControllerPtr.
Definition: StateController.cpp:540
armarx::StateController::findTransition
bool findTransition(const std::string &eventName, const std::string sourceStateName, TransitionIceBase &transition)
Definition: StateController.cpp:1142
armarx::StateController::__enqueueEvent
virtual void __enqueueEvent(const EventPtr event)
Definition: StateController.cpp:195
armarx::FinalStateBase
Definition: FinalState.h:48
armarx::StateController::transitionFunction
std::function< void(StateController *state, const StateIceBasePtr &nextState, const StateIceBasePtr &previousState)> transitionFunction
Definition: StateController.h:59
armarx::StateController
Definition: StateController.h:55
armarx::StateController::TransitionFunctionMap
std::map< std::string, transitionFunction > TransitionFunctionMap
Definition: StateController.h:60
armarx::Profiler
Definition: ManagedIceObject.h:72
armarx::StateController::disableStateReporting
void disableStateReporting(bool disable=true)
Disables the reporting to profilers for this states during state visits.
Definition: StateController.cpp:1120
armarx::StateController::isRunningTaskFinished
bool isRunningTaskFinished() const
Checks whether the run() function has already finished.
Definition: StateController.cpp:1102
armarx::Profiler::ProfilerSet
std::set< ProfilerPtr > ProfilerSet
Definition: Profiler.h:41
armarx::StateController::_baseOnBreak
virtual bool _baseOnBreak(const EventPtr evt)
Called by StateControllerprocessEvent()-function or parentstate. Must NOT be called by user.
Definition: StateController.cpp:934
armarx::StateController::_baseOnExit
virtual void _baseOnExit()
Called by StateController::processEvent()-function or parentstate. Must NOT be called by user.
Definition: StateController.cpp:852
armarx::StateController::__printTransitionError
void __printTransitionError(const TransitionError &transitionError, const EventPtr &event) const
Definition: StateController.cpp:271
armarx::StateController::__checkExistenceOfTransition
bool __checkExistenceOfTransition(const TransitionIceBase &transition)
Definition: StateController.cpp:631
IceInternal::Handle< StateController >
armarx::StateController::disableRunFunction
void disableRunFunction()
disableRunFunction sets useRunFunction to false and waits (blocking) for the current StateBase::run()...
Definition: StateController.cpp:1176
armarx::StateController::__substatesFinished
virtual void __substatesFinished(const EventPtr ev)
Function that gets called, when a state enters a FinalSubstate. Virtual function, so that RemoteState...
Definition: StateController.cpp:167
armarx::RemoteStateOfferer
Class that holds states, which offer functionality for other states over Ice.
Definition: RemoteStateOfferer.h:182
armarx::StateController::getTransitionID
std::string getTransitionID(const TransitionIceBase &t) const
Definition: StateController.cpp:1131
armarx::StateController::__breakActiveSubstate
virtual bool __breakActiveSubstate(const EventPtr event)
Definition: StateController.cpp:559
armarx::StateController::_baseRun
virtual void _baseRun()
Definition: StateController.cpp:827
armarx::StateController::Impl
Definition: StateControllerImpl.h:12
armarx::StateController::isRunningTaskStopped
bool isRunningTaskStopped() const
isRunningTaskStopped checks whether the RunningTask, that executes run() is requested to stop.
Definition: StateController.cpp:1091
armarx::StatechartContext
This class contains a statechart and provides the interfaces to distributed components.
Definition: StatechartContext.h:89
armarx::StateController::__waitForRemoteStates
void __waitForRemoteStates() const
Definition: StateController.cpp:608
armarx::StateController::addTransitionFunction
void addTransitionFunction(const TransitionIceBase &t, transitionFunction function)
Definition: StateController.cpp:1125
armarx::RemoteState
This Statetype is used to create a state instance that represents a state that is located in another ...
Definition: RemoteState.h:62
armarx::DynamicRemoteState
DynamicRemoteStates can be used to connect to remote statecharts dynamically at runtime.
Definition: DynamicRemoteState.h:52
armarx::StateController::removeProfilerRecursive
void removeProfilerRecursive(Profiler::ProfilerPtr profiler, int recursiveLevels=0)
Definition: StateController.cpp:1061
armarx::StateController::_startRun
virtual void _startRun()
Definition: StateController.cpp:808
armarx::StateController::__findValidTransition
bool __findValidTransition(const EventPtr &event, const StateIceBasePtr &sourceState, TransitionIceBase &resultTransition, TransitionError &error) const
Definition: StateController.cpp:420
armarx::StateController::__applyMappings
bool __applyMappings(const StateControllerPtr &srcState, const TransitionIceBase &t, const EventPtr &event, TransitionError &error)
Apply the mappings during a transitions.
Definition: StateController.cpp:211
armarx::StateController::~StateController
~StateController() override
Definition: StateController.cpp:68
boost::source
Vertex source(const detail::edge_base< Directed, Vertex > &e, const PCG &)
Definition: point_cloud_graph.h:681
armarx::StateController::cimpl
std::unique_ptr< Impl > cimpl
Definition: StateController.h:173
armarx::StateController::__getUnbreakableBufferStati
virtual bool __getUnbreakableBufferStati() const
Before:Function to get the unbreakable-buffer status of all parent state - recursively.
Definition: StateController.cpp:1159
armarx::State
Definition: State.h:54
armarx::StateController::isFinished
bool isFinished() const
Definition: StateController.cpp:84
armarx::StateBase
Definition: StateBase.h:61
armarx::StateController::__processBufferedEvents
virtual void __processBufferedEvents()
Processes buffered events, that could not be processed immediately due to unbreakable substates.
Definition: StateController.cpp:582
armarx::TransitionError
Definition: StateUtilFunctions.h:58
armarx::StateUtility
Definition: StateUtil.h:47
armarx::StateController::__finalize
virtual void __finalize(const EventPtr event)
Function that gets called, when a state enters a FinalSubstate. Virtual function, so that RemoteState...
Definition: StateController.cpp:188
StateBase.h
armarx::StateController::_removeInstalledConditions
virtual void _removeInstalledConditions()
This function is implemented in StateUtil and removes all conditions that have been installed in onEn...
Definition: StateController.h:201
armarx::StateController::enter
void enter(const StringVariantContainerBaseMap &tempInputParameters=StringVariantContainerBaseMap())
Function to set the statemachine in the first state and call OnEnter().
Definition: StateController.cpp:121
armarx::StateController::StateController
StateController()
Definition: StateController.cpp:50
armarx::Profiler::ProfilerPtr
std::shared_ptr< Profiler > ProfilerPtr
Definition: ManagedIceObject.h:75
armarx::StateController::waitForRunningTaskToFinish
void waitForRunningTaskToFinish() const
Waits until the run-function has finished.
Definition: StateController.cpp:1111
armarx::StateController::addProfilerRecursive
void addProfilerRecursive(Profiler::ProfilerPtr profiler, int recursiveLevels=0)
addProfilerRecursive recursively adds a new armarx::Profiler::Profiler object as armarx::StateControl...
Definition: StateController.cpp:1033
armarx::StatechartEventDistributor
The StatechartEventDistributor class is used to distribute incomming events (via Ice) to the correct ...
Definition: StatechartEventDistributor.h:65
armarx::StateController::__getUnbreakableBufferSize
virtual unsigned int __getUnbreakableBufferSize() const
Definition: StateController.cpp:514
armarx::StateControllerPtr
IceInternal::Handle< StateController > StateControllerPtr
Definition: StatechartEventDistributor.h:38
armarx::StateController::__notifyEventBufferedDueToUnbreakableState
virtual void __notifyEventBufferedDueToUnbreakableState(bool eventBuffered=true)
Definition: StateController.cpp:519
armarx
This file offers overloads of toIce() and fromIce() functions for STL container types.
Definition: ArmarXTimeserver.cpp:28
armarx::StateController::_baseOnEnter
virtual void _baseOnEnter()
Called by StateControllerprocessEvent()-function or parentstate.
Definition: StateController.cpp:649
armarx::StatechartManager
Definition: StatechartManager.h:42
armarx::StateController::waitForStateToFinish
void waitForStateToFinish(int timeoutMs=-1) const
waitForStateToFinish waits until this thread has finished (i.e.
Definition: StateController.cpp:91