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