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
45namespace armarx
46{
47 //TODO: Move Statecharts into own namespace
48 class StateBase;
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
87 virtual StateParameterMap getInputParameters() = 0;
88
89 virtual StateParameterMap& getOutputParameters();
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);
148 StateBase& operator=(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);
247 void setParameterContainer(StateParameterMap& paramMap,
248 const std::string& key,
249 const VariantContainerBasePtr& valueContainer);
250 void setParameterContainer(StateParameterMap& paramMap,
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
308
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);
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
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
constexpr T c
This class is the implementation of the Slice Definition of a state.
Definition StateBase.h:60
void getParameterContainer(const StateParameterMap &paramMap, const std::string &key, VariantContainerBasePtr &valueContainer) const
virtual void defineState()
Virtual function, in which this state can be configured.
Definition StateBase.h:168
StateBase & operator=(const StateBase &source)
Definition StateBase.cpp:97
virtual void run()
Virtual function, that can be reimplemented to calculate complex operations.
virtual bool isInitialized() const
Returns the status of this state. Only if a state is initialized, it can be used.
StateBasePtr findSubstateByName(const std::string &substateName)
Utility function to find a substate of this state by the name.
void __updateGlobalStateId()
bool isParameterSet(const StateParameterMap &paramMap, const std::string &key) const
virtual StateBasePtr createEmptyCopy() const =0
void setParameter(StateParameterMap &paramMap, const std::string &key, const Variant &variant)
virtual bool __hasActiveSubstate()
Virtual function to indicate wheter a state has an active substate or not. To be overridden by Remote...
static std::vector< StateBasePtr > GetActiveStateLeafs(StateBasePtr toplevelState)
void __setParentState(StateBase *parentState)
virtual bool waitForInitialization(int timeoutMS=-1) const
void __checkPhase(StatePhase allowedType, const char *functionName) const
Helper function for checking if a function was called in valid position of the statechart.
void __checkPhaseMin(StatePhase allowedType, const char *functionName) const
virtual void onBreak()
Virtual function, in which the behaviour of state is defined, when it is abnormally exited....
void setContext(StatechartContextInterface *context)
void inheritInputParameters()
void setStatePhase(StatePhase newPhase)
bool addParameterContainer(StateParameterMap &paramMap, const std::string &key, const ContainerType &containerType, bool optional, VariantContainerBasePtr defaultValue=VariantContainerBasePtr()) const
EventPtr getTriggeredEndstateEvent() const
This function returns the event that was triggered by entering an endstate.
void setStateClassName(std::string className)
setStateClassName() sets the string, that contains a stringrepresentation of this class....
virtual StateParameterMap & getOutputParameters()
virtual StateBasePtr clone() const =0
Pure virtual function to clone of the derived class type.
const std::string & getStateClassName() const
virtual void __updateGlobalStateIdRecursive()
virtual void defineParameters()
Virtual function, in which input/local/output parameters can be specified.
Definition StateBase.h:186
void __copyDefaultValuesToInput()
virtual void defineSubstates()
Virtual function, in which substates, transition and mappings can be added.
Definition StateBase.h:177
void setParameterContainer(StateParameterMap &paramMap, const std::string &key, const VariantContainerBasePtr &valueContainer)
virtual void deepCopy(const StateBase &sourceState, bool reset=true)
Function to copy the states with all it substates and transitions.
virtual void onEnter()
Virtual function, in which the behaviour of state is defined, when it is entered. Can be overridden,...
bool addParameter(StateParameterMap &paramMap, const std::string &key, VariantTypeId type, bool optional, VariantPtr defaultValue=VariantPtr()) const
std::string getLocalHierarchyString() const
Function to get a string that contains als parent states and this state. (e.g. "Robot->Functional->Id...
bool init(StatechartContextInterface *context, StatechartManager *manager)
Function to initialize this state. Must be called in the highest level of the hierarchy - and only th...
std::unique_ptr< Impl > impl
Definition StateBase.h:289
StatePhase
enum that specifies the phase in which the state is currently in used to control the usage of state-f...
Definition StateBase.h:296
StatePhase getStatePhase() const
std::string getGlobalHierarchyString() const
~StateBase() override
virtual bool __hasSubstates()
Virtual function to indicate wheter a state has substates or not. To be overridden by RemoteState to ...
StringVariantContainerBaseMap __getSetInputAndLocalParameters() const
Combines both maps to one map and returns a new map of only the set parameters.
void __throwUnknownParameter(const StateParameterMap &paramMap, const std::string &key) const
Ice::Int getLocalUniqueId() const
void reset()
Function to reset the state: clear name, clear substatesList, clear transition etc.
void getParameter(const StateParameterMap &paramMap, const std::string &key, VariantPtr &value) const
virtual void refetchSubstates()
This functions updates the substates.
ContextType * getContext() const
Definition StateBase.h:71
std::string getStateName() const
getStateName
void setInitialized(bool enable)
virtual void onExit()
Virtual function, in which the behaviour of state is defined, when it is exited. Can be overridden,...
virtual StateParameterMap getInputParameters()=0
Not const because RemoteState implementation gets the current parameters via Ice and sets them.
The Variant class is described here: Variants.
Definition Variant.h:224
This file offers overloads of toIce() and fromIce() functions for STL container types.
IceInternal::Handle< Variant > VariantPtr
Definition Variant.h:41
Ice::Int VariantTypeId
Definition Variant.h:43
IceInternal::Handle< Event > EventPtr
Typedef of EventPtr as IceInternal::Handle<Event> for convenience.
Definition Event.h:40
IceInternal::Handle< StateBase > StateBasePtr
Definition StateBase.h:49
~eUnexpectedEvent() noexcept override
Definition StateBase.h:119
eUnexpectedEvent(const EventPtr event, StateIceBasePtr state)
Definition StateBase.h:112
std::string name() const override
Definition StateBase.h:124