StateBase.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 ArmarXCore::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 #pragma once
25 
26 // ArmarX Includes
28 #include <ArmarXCore/interface/statechart/StatechartIce.h>
31 #include "ParameterMapping.h"
32 #include "Exception.h"
33 #include "StateUtilFunctions.h"
36 
37 
38 #include <memory>
39 #include <vector>
40 
41 
42 #define EVENTTOALL "toAll"
43 #define STATEINFO ARMARX_INFO << armarx::LogTag("State: "+ stateName)
44 
45 
46 namespace armarx
47 {
48  //TODO: Move Statecharts into own namespace
49  class StateBase;
51  class StatechartManager;
52 
53 
54  /**
55  * \class StateBase
56  * \ingroup StatechartGrp
57  * This class is the implementation of the Slice Definition of a state.
58  * It is the baseclass for most statechart related classes.
59  * Basic functionality like data member handling is implemented here.
60  */
61  class StateBase :
62  virtual public StateIceBase,
63  virtual public Logging
64  {
65  public:
66  /*! \brief Function to initialize this state. Must be called in the
67  * highest level of the hierarchy - and only there.
68  */
69  bool init(StatechartContextInterface* context, StatechartManager* manager);
70 
71  StatechartContextInterface* getContext(bool checkNULL = true) const;
72 
73  template <typename ContextType>
74  ContextType* getContext() const
75  {
76  ContextType* c = dynamic_cast<ContextType*>(getContext());
77 
78  if (!c)
79  {
80  throw exceptions::local::eNullPointerException("Could not cast context to requested type!");
81  }
82 
83  return c;
84  }
86 
87  //! Not const because RemoteState implementation gets the current parameters via Ice and sets them
89 
91 
92  /*!
93  * \brief getStateName
94  * \return
95  */
96  std::string getStateName() const;
97  Ice::Int getLocalUniqueId() const;
98  const std::string& getStateClassName() const;
99 
100  /*! \brief Pure virtual function to clone of the derived class type.
101 
102  Implemented function should create a new instance with new and return the StateBasePtr. The new instance should contain a reseted, but initialized version of the original.
103  */
104  virtual StateBasePtr clone() const = 0;
105  virtual StateBasePtr createEmptyCopy() const = 0;
106 
107  //! \brief Function to get a string that contains als parent states and this state. (e.g. "Robot->Functional->Idling")
108  std::string getLocalHierarchyString() const;
109  std::string getGlobalHierarchyString() const;
110 
111  struct eUnexpectedEvent: LocalException
112  {
113  eUnexpectedEvent(const EventPtr event, StateIceBasePtr state) :
114  LocalException("The state '" + state->stateName + "' does not expect the event '" + event->eventName + "' (EventReceiverState: '" + event->eventReceiverName + "')")
115  {
116  }
117  ~eUnexpectedEvent() noexcept override
118  {}
119  std::string name() const override
120  {
121  return "eUnexpectedEvent";
122  }
123  };
124 
125  virtual bool waitForInitialization(int timeoutMS = -1) const;
126  /*!
127  * @brief Returns the status of this state. Only if a state is initialized,
128  * it can be used.
129  * @return Status of state.
130  */
131  virtual bool isInitialized() const;
132  /*!
133  * @brief Utility function to find a substate of this state by the name.
134  *
135  * If somehow multiple state with the same name exist, the first state is returned.
136  * @param substateName
137  * @return Pointer to the requested state, or NULL if not found.
138  */
139  StateBasePtr findSubstateByName(const std::string& substateName);
140 
141  StateBase();
142  StateBase(const StateBase& source);
144 
145  ~StateBase() override;
146 
147  /** Function to copy the states with all it substates and transitions.
148  Creates new copies of all substates and copies them as well.
149  **/
150  virtual void deepCopy(const StateBase& sourceState, bool reset = true);
151 
152  /**
153  *Function to reset the state: clear name, clear substatesList, clear
154  *transition etc.
155  **/
156  void reset();
157 
158  /*! \brief Virtual function, in which this state can be configured.
159 
160  Function gets automatically called in init();
161  */
162  virtual void defineState() {}
163 
164  /*!
165  *\brief Virtual function, in which substates, transition and mappings
166  *can be added.
167  */
168  virtual void defineSubstates() {}
169 
170  /*!
171  *\brief Virtual function, in which input/local/output parameters can
172  *be specified.
173  */
174  virtual void defineParameters() {}
175 
176  /*! \brief Virtual function, in which the behaviour of state is
177  defined, when it is <b>entered</b>.<br/> Can be overridden, but it is
178  optional.
179  */
180  virtual void onEnter();
181 
182 
183  /**
184  * @brief Virtual function, that can be reimplemented to calculate
185  * complex operations. It runs in it's own thread.<br/>
186  *
187  * This function is called after onEnter(). This function can continue
188  * to run even if the
189  * state has been left (onExit() has been called), but all calculations
190  * will be discarded (Output- and Localparameters will be reseted).<br/>
191  * Calls to <b>external components</b> will still be executed!<br/>
192  * Calls to sendEvent() will be ignored, after the state has been left.
193  *
194  * @note Before re-entering this state, the state waits for this
195  * function from the last state-visit to complete. The implementation
196  * of run should constantly check, if StateController::isRunningTaskStopped()
197  * returns true and exit the run-function in that case.
198  */
199  virtual void run();
200 
201 
202  /*! \brief Virtual function, in which the behaviour of state is
203  defined, when it is \b exited. Can be overridden, but it is optional.
204  \see onBreak()
205  */
206  virtual void onExit();
207 
208  /*! \brief Virtual function, in which the behaviour of state is
209  defined, when it is abnormally exited. Can be overridden, but it is
210  optional. <br/> An abnormal exit only occurs in
211  hierarchy-levels greater 1.<br/> When a parent state is left before the
212  substates are finished, the OnBreak()-function is called in the active
213  substate and in all it's active substates.<br/> If this function is not
214  implemented, the normal OnExit()-function is called.<br/>
215  \see onExit()
216  */
217  virtual void onBreak();
218 
219 
220 
221 
222  bool addParameter(StateParameterMap& paramMap, const std::string& key, VariantTypeId type, bool optional, VariantPtr defaultValue = VariantPtr()) const;
223  bool addParameterContainer(StateParameterMap& paramMap, const std::string& key, const ContainerType& containerType, bool optional, VariantContainerBasePtr defaultValue = VariantContainerBasePtr()) const;
224  void setParameter(StateParameterMap& paramMap, const std::string& key, const Variant& variant);
225  void setParameterContainer(StateParameterMap& paramMap, const std::string& key, const VariantContainerBasePtr& valueContainer);
226  void setParameterContainer(StateParameterMap& paramMap, const std::string& key, const VariantContainerBase& valueContainer);
227 
228 
229  void getParameter(const StateParameterMap& paramMap, const std::string& key, VariantPtr& value) const;
230  void getParameterContainer(const StateParameterMap& paramMap, const std::string& key, VariantContainerBasePtr& valueContainer) const;
231 
232  bool isParameterSet(const StateParameterMap& paramMap, const std::string& key) const;
233  /*!
234  * \brief setStateClassName() sets the string, that contains a
235  * stringrepresentation of this class. Should not be called usually.
236  * The classname gets automatically set in the constructor of the
237  * derived class StateTemplate<T>.
238  *
239  *
240  * \param className Stringrepresentation of the classname (e.g. StateBase for this class)
241  */
242  void setStateClassName(std::string className);
243 
244  /**
245  * @brief This functions updates the substates. For local states only
246  * calls the substates refetch function, but for remoteStates requests the
247  * data via Ice.
248  */
249  virtual void refetchSubstates();
250 
251  /**
252  * @brief This function returns the event that was triggered by entering an endstate.
253  * This is useful in the onExit() function to determine which endstate of the substates was triggered.
254  * @return Event that was triggered, NULL if no endstate was reached
255  */
257 
258  struct Impl;
259  std::unique_ptr<Impl> impl;
260 
261  void setInitialized(bool enable);
262 
263  //! enum that specifies the phase in which the state is currently in
264  //! used to control the usage of state-functions in the correct context
266  {
277  };
278 
279  StatePhase getStatePhase() const;
280  void setStatePhase(StatePhase newPhase);
281  //! Helper function for checking if a function was called in valid position of the statechart
282  //! @throw LocalException if allowedType does not match the current phase type
283  void __checkPhase(StatePhase allowedType, const char* functionName) const;
284  void __checkPhase(const std::vector<StatePhase>& allowedTypes, const char* functionName) const;
285  void __checkPhaseMin(StatePhase allowedType, const char* functionName) const;
286  void __throwUnknownParameter(const StateParameterMap& paramMap, const std::string& key) const;
287 
289 
290  void clearSelfPointer();
291 
292  void __setParentState(StateBase* parentState);
293  void __updateGlobalStateId();
294  virtual void __updateGlobalStateIdRecursive();
295 
296 
297  /*! \brief Virtual function to indicate wheter a state has substates or
298  not. To be overridden by RemoteState to deligate the call to the real
299  state.
300  */
301  virtual bool __hasSubstates();
302 
303  /*! \brief Virtual function to indicate wheter a state has an
304  <b>active</b> substate or not. To be overridden by RemoteState to
305  deligate the call to the real state.
306  */
307  virtual bool __hasActiveSubstate();
308 
309  void inheritInputParameters();
310 
311 
312  //! Combines both maps to one map and returns a new map of only the set parameters
313  StringVariantContainerBaseMap __getSetInputAndLocalParameters() const;
314 
315  static std::vector<StateBasePtr> GetActiveStateLeafs(StateBasePtr toplevelState);
316  };
317 
318 }
armarx::StateBase::getOutputParameters
virtual StateParameterMap & getOutputParameters()
Definition: StateBase.cpp:518
armarx::StateBase::eEntered
@ eEntered
Definition: StateBase.h:273
armarx::StateBase::getParameterContainer
void getParameterContainer(const StateParameterMap &paramMap, const std::string &key, VariantContainerBasePtr &valueContainer) const
Definition: StateBase.cpp:714
armarx::StateBase::getGlobalHierarchyString
std::string getGlobalHierarchyString() const
Definition: StateBase.cpp:554
armarx::Variant
The Variant class is described here: Variants.
Definition: Variant.h:224
armarx::StateBase::getContext
ContextType * getContext() const
Definition: StateBase.h:74
armarx::StateBase::eEntering
@ eEntering
Definition: StateBase.h:272
armarx::StateBase::defineParameters
virtual void defineParameters()
Virtual function, in which input/local/output parameters can be specified.
Definition: StateBase.h:174
armarx::StateBase::deepCopy
virtual void deepCopy(const StateBase &sourceState, bool reset=true)
Function to copy the states with all it substates and transitions.
Definition: StateBase.cpp:316
armarx::StateBase::setStatePhase
void setStatePhase(StatePhase newPhase)
Definition: StateBase.cpp:850
armarx::StateBase::__getSetInputAndLocalParameters
StringVariantContainerBaseMap __getSetInputAndLocalParameters() const
Combines both maps to one map and returns a new map of only the set parameters.
Definition: StateBase.cpp:856
armarx::StateBase::waitForInitialization
virtual bool waitForInitialization(int timeoutMS=-1) const
Definition: StateBase.cpp:559
armarx::StateBase::onExit
virtual void onExit()
Virtual function, in which the behaviour of state is defined, when it is exited. Can be overridden,...
Definition: StateBase.cpp:506
armarx::StateBase::eStatechartDefinitions
@ eStatechartDefinitions
Definition: StateBase.h:268
armarx::StateBase::eUnexpectedEvent::name
std::string name() const override
Definition: StateBase.h:119
armarx::StateBase::onBreak
virtual void onBreak()
Virtual function, in which the behaviour of state is defined, when it is abnormally exited....
Definition: StateBase.cpp:489
armarx::StateBase::operator=
StateBase & operator=(const StateBase &source)
Definition: StateBase.cpp:98
armarx::StateBase::StatePhase
StatePhase
enum that specifies the phase in which the state is currently in used to control the usage of state-f...
Definition: StateBase.h:265
armarx::StateBase::defineState
virtual void defineState()
Virtual function, in which this state can be configured.
Definition: StateBase.h:162
armarx::StateBase::__checkPhaseMin
void __checkPhaseMin(StatePhase allowedType, const char *functionName) const
Definition: StateBase.cpp:225
armarx::StateBase::eUnexpectedEvent
Definition: StateBase.h:111
armarx::StateBase::getInputParameters
virtual StateParameterMap getInputParameters()=0
Not const because RemoteState implementation gets the current parameters via Ice and sets them.
armarx::StateBase::isInitialized
virtual bool isInitialized() const
Returns the status of this state. Only if a state is initialized, it can be used.
Definition: StateBase.cpp:579
c
constexpr T c
Definition: UnscentedKalmanFilterTest.cpp:43
armarx::StateBase::setInitialized
void setInitialized(bool enable)
Definition: StateBase.cpp:283
armarx::StateBase::getStateName
std::string getStateName() const
getStateName
Definition: StateBase.cpp:523
armarx::StatechartContextInterface
Definition: StatechartContextInterface.h:46
armarx::StateBase::GetActiveStateLeafs
static std::vector< StateBasePtr > GetActiveStateLeafs(StateBasePtr toplevelState)
Definition: StateBase.cpp:864
armarx::StateBase::getLocalUniqueId
Ice::Int getLocalUniqueId() const
Definition: StateBase.cpp:528
armarx::StateBase::createEmptyCopy
virtual StateBasePtr createEmptyCopy() const =0
armarx::exceptions::local::eNullPointerException
Definition: Exception.h:42
armarx::StateBase::StateBase
StateBase()
Definition: StateBase.cpp:51
StateUtilFunctions.h
ParameterMapping.h
armarx::StateBase::clearSelfPointer
void clearSelfPointer()
Definition: StateBase.cpp:240
armarx::StateBase::eDefined
@ eDefined
Definition: StateBase.h:271
armarx::StateBase::__updateGlobalStateId
void __updateGlobalStateId()
Definition: StateBase.cpp:254
armarx::StateBase::__updateGlobalStateIdRecursive
virtual void __updateGlobalStateIdRecursive()
Definition: StateBase.cpp:273
IceInternal::Handle< StateBase >
armarx::StateBase::setParameterContainer
void setParameterContainer(StateParameterMap &paramMap, const std::string &key, const VariantContainerBasePtr &valueContainer)
Definition: StateBase.cpp:685
armarx::VariantPtr
IceInternal::Handle< Variant > VariantPtr
Definition: Variant.h:42
armarx::StateBase::setStateClassName
void setStateClassName(std::string className)
setStateClassName() sets the string, that contains a stringrepresentation of this class....
Definition: StateBase.cpp:824
cxxopts::value
std::shared_ptr< Value > value()
Definition: cxxopts.hpp:926
armarx::StateBase::reset
void reset()
Function to reset the state: clear name, clear substatesList, clear transition etc.
Definition: StateBase.cpp:887
armarx::StateBase::__copyDefaultValuesToInput
void __copyDefaultValuesToInput()
Definition: StateBase.cpp:774
armarx::statechartmodel::StateParameterMap
QMap< QString, StateParameterPtr > StateParameterMap
Definition: StateParameter.h:46
Event.h
armarx::StateBase::~StateBase
~StateBase() override
Definition: StateBase.cpp:106
armarx::StateBase::eExited
@ eExited
Definition: StateBase.h:276
armarx::StateBase::inheritInputParameters
void inheritInputParameters()
Definition: StateBase.cpp:755
armarx::VariantTypeId
Ice::Int VariantTypeId
Definition: Variant.h:44
boost::source
Vertex source(const detail::edge_base< Directed, Vertex > &e, const PCG &)
Definition: point_cloud_graph.h:681
armarx::StateBase::addParameter
bool addParameter(StateParameterMap &paramMap, const std::string &key, VariantTypeId type, bool optional, VariantPtr defaultValue=VariantPtr()) const
Definition: StateBase.cpp:585
armarx::StateBase::run
virtual void run()
Virtual function, that can be reimplemented to calculate complex operations.
Definition: StateBase.cpp:500
armarx::StateBase
Definition: StateBase.h:61
armarx::StateBase::__throwUnknownParameter
void __throwUnknownParameter(const StateParameterMap &paramMap, const std::string &key) const
Definition: StateBase.cpp:743
armarx::StateBase::defineSubstates
virtual void defineSubstates()
Virtual function, in which substates, transition and mappings can be added.
Definition: StateBase.h:168
armarx::StateBase::getLocalHierarchyString
std::string getLocalHierarchyString() const
Function to get a string that contains als parent states and this state. (e.g. "Robot->Functional->Id...
Definition: StateBase.cpp:538
armarx::StateBase::ePreDefined
@ ePreDefined
Definition: StateBase.h:267
armarx::StateBase::eSubstatesDefinitions
@ eSubstatesDefinitions
Definition: StateBase.h:269
armarx::Logging
Base Class for all Logging classes.
Definition: Logging.h:232
armarx::StateBase::clone
virtual StateBasePtr clone() const =0
Pure virtual function to clone of the derived class type.
armarx::StateBase::setParameter
void setParameter(StateParameterMap &paramMap, const std::string &key, const Variant &variant)
Definition: StateBase.cpp:662
armarx::StateBase::setContext
void setContext(StatechartContextInterface *context)
Definition: StateBase.cpp:513
armarx::StateBase::refetchSubstates
virtual void refetchSubstates()
This functions updates the substates.
Definition: StateBase.cpp:830
armarx::StateBase::onEnter
virtual void onEnter()
Virtual function, in which the behaviour of state is defined, when it is entered. Can be overridden,...
Definition: StateBase.cpp:496
armarx::StateBase::__setParentState
void __setParentState(StateBase *parentState)
Definition: StateBase.cpp:248
armarx::VariantType::Int
const VariantTypeId Int
Definition: Variant.h:916
armarx::StateBase::addParameterContainer
bool addParameterContainer(StateParameterMap &paramMap, const std::string &key, const ContainerType &containerType, bool optional, VariantContainerBasePtr defaultValue=VariantContainerBasePtr()) const
Definition: StateBase.cpp:602
armarx::StateBase::__hasActiveSubstate
virtual bool __hasActiveSubstate()
Virtual function to indicate wheter a state has an active substate or not. To be overridden by Remote...
Definition: StateBase.cpp:300
armarx::StateBase::getStateClassName
const std::string & getStateClassName() const
Definition: StateBase.cpp:533
armarx::StateBase::isParameterSet
bool isParameterSet(const StateParameterMap &paramMap, const std::string &key) const
Definition: StateBase.cpp:731
Logging.h
armarx::StateBase::getStatePhase
StatePhase getStatePhase() const
Definition: StateBase.cpp:844
armarx::StateBase::eBreaking
@ eBreaking
Definition: StateBase.h:274
armarx::StateBase::eParametersDefinitions
@ eParametersDefinitions
Definition: StateBase.h:270
armarx::StateBase::eUnexpectedEvent::~eUnexpectedEvent
~eUnexpectedEvent() noexcept override
Definition: StateBase.h:117
armarx::StateBase::eExiting
@ eExiting
Definition: StateBase.h:275
armarx::StateBase::getTriggeredEndstateEvent
EventPtr getTriggeredEndstateEvent() const
This function returns the event that was triggered by entering an endstate.
Definition: StateBase.cpp:839
armarx::StateBase::__hasSubstates
virtual bool __hasSubstates()
Virtual function to indicate wheter a state has substates or not. To be overridden by RemoteState to ...
Definition: StateBase.cpp:290
Variant.h
armarx::StateBase::__checkPhase
void __checkPhase(StatePhase allowedType, const char *functionName) const
Helper function for checking if a function was called in valid position of the statechart.
Definition: StateBase.cpp:134
armarx::StateBase::impl
std::unique_ptr< Impl > impl
Definition: StateBase.h:258
armarx::StateBase::findSubstateByName
StateBasePtr findSubstateByName(const std::string &substateName)
Utility function to find a substate of this state by the name.
Definition: StateBase.cpp:788
armarx::StateBase::Impl
Definition: StateBaseImpl.h:10
armarx
This file offers overloads of toIce() and fromIce() functions for STL container types.
Definition: ArmarXTimeserver.cpp:28
Exception.h
armarx::StatechartManager
Definition: StatechartManager.h:42
armarx::StateBase::eUnexpectedEvent::eUnexpectedEvent
eUnexpectedEvent(const EventPtr event, StateIceBasePtr state)
Definition: StateBase.h:113
armarx::StateBase::getParameter
void getParameter(const StateParameterMap &paramMap, const std::string &key, VariantPtr &value) const
Definition: StateBase.cpp:801
StatechartContextInterface.h
armarx::StateBase::init
bool init(StatechartContextInterface *context, StatechartManager *manager)
Function to initialize this state. Must be called in the highest level of the hierarchy - and only th...
Definition: StateBase.cpp:420