SMACC2
Loading...
Searching...
No Matches
smacc_state_base.hpp
Go to the documentation of this file.
1// Copyright 2025 Robosoft Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15/*****************************************************************************************************************
16 *
17 * Authors: Pablo Inigo Blasco, Brett Aldrich
18 *
19 ******************************************************************************************************************/
20
21#pragma once
29
30#define STATE_NAME (demangleSymbol(typeid(MostDerived).name()).c_str())
31
32namespace smacc2
33{
34// Posts EvStInitializationFailure<TAddressee> for a failure in stateName. The event carries the
35// call that addresses it to the addressee's own container, until the container is the state machine.
36template <typename TAddressee>
38 ISmaccStateMachine * stateMachine, const std::string & stateName, const std::string & what)
39{
41 ev->stateName = stateName;
42 ev->what = what;
43 using TContainer = typename TAddressee::context_type;
44 if constexpr (!std::is_base_of<ISmaccStateMachine, TContainer>::value)
45 {
46 ev->escalate = [stateMachine, stateName, what]()
47 { postStInitializationFailure<TContainer>(stateMachine, stateName, what); };
48 }
49 stateMachine->postEvent(ev, EventLifeTime::CURRENT_STATE);
50}
51
52using namespace smacc2::introspection;
53using namespace smacc2::default_events;
54
55template <
56 class MostDerived, class Context, class InnerInitial = mpl::list<>,
57 sc::history_mode historyMode = sc::has_deep_history>
58class SmaccState : public sc::simple_state<MostDerived, Context, InnerInitial, historyMode>,
59 public ISmaccState
60{
62
63public:
64 typedef Context TContext;
65 typedef typename Context::inner_context_type context_type;
66 typedef typename context_type::state_iterator state_iterator;
67
68 typedef InnerInitial LastDeepState;
69
71 InnerInitial * smacc_inner_type;
72
75 {
76 my_context(typename base_type::context_ptr_type pContext) : pContext_(pContext) {}
77
78 typename base_type::context_ptr_type pContext_;
79 };
80
81 SmaccState() = delete;
82
83 // Constructor that initializes the state ros node handle
85 {
86 static_assert(
87 std::is_base_of<ISmaccState, Context>::value ||
88 std::is_base_of<ISmaccStateMachine, Context>::value,
89 "The context class must be a SmaccState or a SmaccStateMachine");
90 static_assert(
91 !std::is_same<MostDerived, Context>::value,
92 "The context must be a different state or state machine "
93 "than the current state");
94
95 logger_ = std::make_shared<rclcpp::Logger>(
96 rclcpp::get_logger(smacc2::utils::cleanShortTypeName(typeid(MostDerived))));
97
98 RCLCPP_INFO(getLogger(), "[%s] Creating state ", STATE_NAME);
99 this->set_context(ctx.pContext_);
100
101 node_ = this->getStateMachine().getNode();
102
103 this->stateInfo_ = getStateInfo();
104
105 // storing a reference to the parent state
106 auto & ps = this->template context<Context>();
107 parentState_ = dynamic_cast<ISmaccState *>(&ps);
108 finishStateThrown = false;
109 }
110
111 virtual ~SmaccState() {}
112
114 {
115 // By reference: a plain `auto` copied the whole SmaccStateMachineInfo on every state construction.
116 const auto & smInfo = this->getStateMachine().getStateMachineInfo();
117
118 auto it = smInfo.states.find(typeid(MostDerived).name());
119 return it != smInfo.states.end() ? it->second.get() : nullptr;
120 }
121
122 std::string getName() override { return getShortName(); }
123
124 std::string getFullName() { return demangleSymbol(typeid(MostDerived).name()); }
125
126 std::string getShortName() { return smacc2::utils::cleanShortTypeName(typeid(MostDerived)); }
127
129
130 // this function is called by boot statechart before the destructor call
131 void exit()
132 {
133 auto * derivedThis = static_cast<MostDerived *>(this);
134 {
135 std::lock_guard<std::recursive_mutex> lock(this->getStateMachine().getMutex());
136 this->getStateMachine().notifyOnStateExiting(derivedThis);
137 try
138 {
139 TRACETOOLS_TRACEPOINT(smacc2_state_onExit_start, STATE_NAME);
140 // A state whose initialization failed was never entered, so its onExit does not run.
141 if (!this->initializationFailed_) standardOnExit(*derivedThis);
142 TRACETOOLS_TRACEPOINT(smacc2_state_onExit_end, STATE_NAME);
143 }
144 // The exit path must complete, so the exception is logged and swallowed, not propagated.
145 catch (const std::exception & e)
146 {
147 RCLCPP_ERROR(getLogger(), "[%s] exception in onExit: %s", STATE_NAME, e.what());
148 }
149 catch (...)
150 {
151 RCLCPP_ERROR(getLogger(), "[%s] non-standard exception in onExit", STATE_NAME);
152 }
153 this->getStateMachine().notifyOnStateExited(derivedThis);
154 }
155 }
156
157public:
158 // This method is static-polymorphic because of the curiously recurring template pattern. It
159 // calls to the most derived class onEntry method if declared on smacc state construction
161
162 // This method is static-polymorphic because of the curiously recurring template pattern. It
163 // calls to the most derived class onEntry method if declared on smacc state construction
164 void onEntry() {}
165
166 // this method is static-polimorphic because of the curiously recurreing pattern. It
167 // calls to the most derived class onExit method if declared on smacc state destruction
168 void onExit() {}
169
170 template <typename T>
171 bool getGlobalSMData(const std::string & name, T & ret)
172 {
173 return base_type::outermost_context().getGlobalSMData(name, ret);
174 }
175
176 // Store globally in this state machine. (By value parameter )
177 template <typename T>
178 void setGlobalSMData(const std::string & name, T value)
179 {
180 base_type::outermost_context().setGlobalSMData(name, value);
181 }
182
183 // requiresComponent and requiresClient come from ISmaccState; a copy here would shadow the
184 // base overload set.
185
186 ISmaccStateMachine & getStateMachine() override { return base_type::outermost_context(); }
187
188 template <typename TOrthogonal, typename TBehavior>
190 std::function<void(TBehavior & bh, MostDerived &)> initializationFunction)
191 {
193 [=](ISmaccState * state)
194 {
195 auto bh = state->configure<TOrthogonal, TBehavior>();
196 initializationFunction(*bh, *(static_cast<MostDerived *>(state)));
197 });
198 }
199
200 template <typename TOrthogonal, typename TBehavior>
202 std::function<void(TBehavior & bh)> initializationFunction)
203 {
205 [=](ISmaccState * state)
206 {
207 auto bh = state->configure<TOrthogonal, TBehavior>();
208 initializationFunction(*bh);
209 });
210 }
211
212 template <typename TOrthogonal, typename TBehavior, typename... Args>
213 static void configure_orthogonal(Args &&... args)
214 {
216 [=](ISmaccState * state) { state->configure<TOrthogonal, TBehavior>(args...); });
217 }
218
219 template <
220 typename TStateReactor, typename TOutputEvent, typename TInputEventList, typename... TArgs>
221 static std::shared_ptr<smacc2::introspection::StateReactorHandler> static_createStateReactor(
222 TArgs... args)
223 {
224 auto srh = std::make_shared<smacc2::introspection::StateReactorHandler>(globalNh_);
225 auto srinfo = std::make_shared<SmaccStateReactorInfo>();
226
227 srinfo->stateReactorType = TypeInfo::getTypeInfoFromType<TStateReactor>();
228 srinfo->outputEventType = TypeInfo::getTypeInfoFromType<TOutputEvent>();
229
230 if (srinfo->outputEventType->templateParameters.size() == 2)
231 {
232 srinfo->objectTagType = srinfo->outputEventType->templateParameters[1];
233 }
234 else if (srinfo->outputEventType->templateParameters.size() == 1)
235 {
237 }
238 else
239 {
240 assert(
241 false &&
242 "state reactor output events should have one or two parameters (SourceType, ObjectTag)");
243 }
244
245 // iterate statically on all event sources
246 using boost::mpl::_1;
247 using wrappedList = typename boost::mpl::transform<TInputEventList, _1>::type;
249 boost::mpl::for_each<wrappedList>(op);
250
251 srinfo->srh = srh;
252 srh->srInfo_ = srinfo;
253
254 const std::type_info * tindex = &(typeid(MostDerived)); // get identifier of the current state
255
256 if (!SmaccStateInfo::stateReactorsInfo.count(tindex))
258 std::vector<std::shared_ptr<SmaccStateReactorInfo>>();
259
260 srinfo->factoryFunction = [&, srh, args...](ISmaccState * state)
261 {
262 auto sr =
263 state->createStateReactor<TStateReactor, TOutputEvent, TInputEventList, TArgs...>(args...);
264 srh->configureStateReactor(sr);
265 sr->initialize(state);
266 return sr;
267 };
268
269 SmaccStateInfo::stateReactorsInfo[tindex].push_back(srinfo);
270
271 return srh;
272 }
273
274 template <typename TEventGenerator, typename... TUArgs>
275 static std::shared_ptr<smacc2::introspection::EventGeneratorHandler> static_createEventGenerator(
276 TUArgs... args)
277 {
278 auto egh = std::make_shared<smacc2::introspection::EventGeneratorHandler>();
279 auto eginfo = std::make_shared<SmaccEventGeneratorInfo>();
280 eginfo->eventGeneratorType = TypeInfo::getTypeInfoFromType<TEventGenerator>();
281
282 eginfo->egh = egh;
283 egh->egInfo_ = eginfo;
284
285 const std::type_info * tindex = &(typeid(MostDerived)); // get identifier of the current state
286
287 if (!SmaccStateInfo::eventGeneratorsInfo.count(tindex))
289 std::vector<std::shared_ptr<SmaccEventGeneratorInfo>>();
290
291 eginfo->factoryFunction = [&, egh, args...](ISmaccState * state)
292 {
293 auto eg = state->createEventGenerator<TEventGenerator>(args...);
294 egh->configureEventGenerator(eg);
295 eg->initialize(state);
296
297 eg->template onStateOrthogonalAllocation<MostDerived, TEventGenerator>();
298 return eg;
299 };
300
301 SmaccStateInfo::eventGeneratorsInfo[tindex].push_back(eginfo);
302 return egh;
303 }
304
305 template <typename TStateReactor, typename... TUArgs>
306 static std::shared_ptr<smacc2::introspection::StateReactorHandler> static_createStateReactor_aux(
307 TUArgs... args)
308 {
309 auto srh = std::make_shared<smacc2::introspection::StateReactorHandler>(globalNh_);
310 auto srinfo = std::make_shared<SmaccStateReactorInfo>();
311
312 srinfo->stateReactorType = TypeInfo::getTypeInfoFromType<TStateReactor>();
313 srinfo->srh = srh;
314 srh->srInfo_ = srinfo;
315
316 const std::type_info * tindex = &(typeid(MostDerived)); // get identifier of the current state
317
318 if (!SmaccStateInfo::stateReactorsInfo.count(tindex))
320 std::vector<std::shared_ptr<SmaccStateReactorInfo>>();
321
322 srinfo->factoryFunction = [&, srh, args...](ISmaccState * state)
323 {
324 auto sr = state->createStateReactor<TStateReactor>(args...);
325 srh->configureStateReactor(sr);
326 sr->initialize(state);
327 return sr;
328 };
329
330 SmaccStateInfo::stateReactorsInfo[tindex].push_back(srinfo);
331
332 return srh;
333 }
334
335 void checkWhileLoopConditionAndThrowEvent(bool (MostDerived::*conditionFn)())
336 {
337 auto * thisobject = static_cast<MostDerived *>(this);
338 auto condition = boost::bind(conditionFn, thisobject);
339 bool conditionResult = condition();
340
341 // RCLCPP_INFO("LOOP EVENT CONDITION: %d", conditionResult);
342 if (conditionResult)
343 {
345 }
346 else
347 {
348 this->template postEvent<EvLoopEnd<MostDerived>>();
349 }
350 RCLCPP_INFO(getLogger(), "[%s] POST THROW CONDITION", STATE_NAME);
351 }
352
354
356 // The following declarations should be private.
357 // They are only public because many compilers lack template friends.
359 // See base class for documentation
360 typedef typename base_type::outermost_context_base_type outermost_context_base_type;
361 typedef typename base_type::inner_context_ptr_type inner_context_ptr_type;
362 typedef typename base_type::context_ptr_type context_ptr_type;
363 typedef typename base_type::inner_initial_list inner_initial_list;
364
365 static void initial_deep_construct(outermost_context_base_type & outermostContextBase)
366 {
367 deep_construct(&outermostContextBase, outermostContextBase);
368 }
369
370 // See base class for documentation
371 static void deep_construct(
372 const context_ptr_type & pContext, outermost_context_base_type & outermostContextBase)
373 {
374 const inner_context_ptr_type pInnerContext(shallow_construct(pContext, outermostContextBase));
375 base_type::template deep_construct_inner<inner_initial_list>(
376 pInnerContext, outermostContextBase);
377 }
378
380 const context_ptr_type & pContext, outermost_context_base_type & outermostContextBase)
381 {
382 // Boost.Statechart's construction protocol; owned by pInnerContext below (MISRA C++:2023 21.6.2 deviation).
383 auto state = new MostDerived(
385 const inner_context_ptr_type pInnerContext(state);
386
387 TRACETOOLS_TRACEPOINT(smacc2_state_onEntry_start, STATE_NAME);
388 state->entryStateInternal();
389 TRACETOOLS_TRACEPOINT(smacc2_state_onEntry_end, STATE_NAME);
390
391 outermostContextBase.add(pInnerContext);
392 return pInnerContext;
393 }
394
395private:
396 template <typename TOrthogonal, typename TBehavior>
398 std::function<void(ISmaccState * state)> initializationFunction)
399 {
401 bhinfo.factoryFunction = initializationFunction;
402
403 bhinfo.behaviorType = &(typeid(TBehavior));
404 bhinfo.orthogonalType = &(typeid(TOrthogonal));
405
406 const std::type_info * tindex = &(typeid(MostDerived));
407 if (!SmaccStateInfo::staticBehaviorInfo.count(tindex))
408 SmaccStateInfo::staticBehaviorInfo[tindex] = std::vector<ClientBehaviorInfoEntry>();
409
410 SmaccStateInfo::staticBehaviorInfo[tindex].push_back(bhinfo);
411 RCLCPP_INFO_STREAM(
412 rclcpp::get_logger("static"), "[states walking] State "
414 << "client behavior count: "
415 << SmaccStateInfo::staticBehaviorInfo[tindex].size());
416 }
417
419 {
420 // finally we go to the derived state onEntry Function
421
422 RCLCPP_DEBUG(getLogger(), "[%s] State object created. Initializing...", STATE_NAME);
423 this->getStateMachine().notifyOnStateEntryStart(static_cast<MostDerived *>(this));
424
425 RCLCPP_DEBUG_STREAM(
426 getLogger(), "[" << smacc2::utils::cleanShortTypeName(typeid(MostDerived)).c_str()
427 << "] creating ros subnode");
428
429 // before dynamic runtimeConfigure, we execute the staticConfigure behavior configurations
430 {
431 RCLCPP_DEBUG(getLogger(), "[%s] -- STATIC STATE DESCRIPTION --", STATE_NAME);
432
433 for (const auto & clientBehavior : SmaccStateInfo::staticBehaviorInfo)
434 {
435 RCLCPP_DEBUG(
436 getLogger(), "[%s] client behavior info: %s", STATE_NAME,
437 demangleSymbol(clientBehavior.first->name()).c_str());
438 for (auto & cbinfo : clientBehavior.second)
439 {
440 RCLCPP_DEBUG(
441 getLogger(), "[%s] client behavior: %s", STATE_NAME,
442 demangleSymbol(cbinfo.behaviorType->name()).c_str());
443 }
444 }
445
446 const std::type_info * tindex = &(typeid(MostDerived));
447 auto & staticDefinedBehaviors = SmaccStateInfo::staticBehaviorInfo[tindex];
448 auto & staticDefinedStateReactors = SmaccStateInfo::stateReactorsInfo[tindex];
449 auto & staticDefinedEventGenerators = SmaccStateInfo::eventGeneratorsInfo[tindex];
450
451 for (auto & ortho : this->getStateMachine().getOrthogonals())
452 {
453 RCLCPP_INFO(
454 getLogger(), "[%s] Initializing orthogonal: %s", STATE_NAME,
455 demangleSymbol(typeid(*ortho.second).name()).c_str());
456 ortho.second->initState(this);
457 }
458
459 RCLCPP_DEBUG_STREAM(
460 getLogger(), "Finding static client behaviors. State Database: "
461 << SmaccStateInfo::staticBehaviorInfo.size() << ". Current state "
462 << cleanShortTypeName(*tindex)
463 << " cbs: " << SmaccStateInfo::staticBehaviorInfo[tindex].size());
464 for (auto & bhinfo : staticDefinedBehaviors)
465 {
466 RCLCPP_DEBUG(
467 getLogger(), "[%s] Creating static client behavior: %s", STATE_NAME,
468 demangleSymbol(bhinfo.behaviorType->name()).c_str());
469 bhinfo.factoryFunction(this);
470 }
471
472 for (auto & sr : staticDefinedStateReactors)
473 {
474 RCLCPP_DEBUG(
475 getLogger(), "[%s] Creating static state reactor: %s", STATE_NAME,
476 sr->stateReactorType->getFullName().c_str());
477 sr->factoryFunction(this);
478 }
479
480 for (auto & eg : staticDefinedEventGenerators)
481 {
482 RCLCPP_DEBUG(
483 getLogger(), "[%s] Creating static event generator: %s", STATE_NAME,
484 eg->eventGeneratorType->getFullName().c_str());
485 eg->factoryFunction(this);
486 }
487
488 RCLCPP_DEBUG(getLogger(), "[%s] ---- END STATIC DESCRIPTION", STATE_NAME);
489 }
490
491 RCLCPP_DEBUG(getLogger(), "[%s] State runtime configuration", STATE_NAME);
492
493 auto * derivedthis = static_cast<MostDerived *>(this);
494
495 // second the orthogonals are internally configured
496 this->getStateMachine().notifyOnRuntimeConfigured(derivedthis);
497
498 // A state inside a container whose initialization failed is not initialized either; the
499 // container's failure event is already posted.
500 if (this->parentState_ != nullptr && this->parentState_->initializationFailed())
501 {
502 RCLCPP_WARN(
503 getLogger(), "[%s] not initialized: its container state failed to initialize", STATE_NAME);
504 this->initializationFailed_ = true;
505 }
506
507 // User code: an exception from runtimeConfigure or onEntry is logged and posted as
508 // EvStInitializationFailure, and the state's client behaviors are then not entered.
509 if (!this->initializationFailed_)
510 {
511 try
512 {
514 // first we runtime configure the state, where we create client behaviors
515 static_cast<MostDerived *>(this)->runtimeConfigure();
516 TRACETOOLS_TRACEPOINT(smacc2_state_onRuntimeConfigure_end, STATE_NAME);
517 }
518 catch (const std::exception & e)
519 {
520 this->onInitializationFailure(e.what());
521 }
522 catch (...)
523 {
524 this->onInitializationFailure("non-standard exception");
525 }
526 }
527
528 // Always runs: it keeps the per-state bookkeeping that the exit path undoes.
530
531 if (!this->initializationFailed_)
532 {
533 RCLCPP_DEBUG(getLogger(), "[%s] State OnEntry", STATE_NAME);
534 try
535 {
536 static_cast<MostDerived *>(this)->onEntry();
537 }
538 catch (const std::exception & e)
539 {
540 this->onInitializationFailure(e.what());
541 }
542 catch (...)
543 {
544 this->onInitializationFailure("non-standard exception");
545 }
546 }
547
548 // here orthogonals and client behaviors are entered OnEntry
549 this->getStateMachine().notifyOnStateEntryEnd(derivedthis);
550 }
551
552 void onInitializationFailure(const std::string & what)
553 {
554 const std::string stateName = demangleSymbol(typeid(MostDerived).name());
555 RCLCPP_ERROR(
556 getLogger(),
557 "[%s] exception in state initialization: %s. Its client behaviors are not started.",
558 stateName.c_str(), what.c_str());
559 this->initializationFailed_ = true;
561 }
562};
563} // namespace smacc2
rclcpp::Node::SharedPtr getNode()
void notifyOnRuntimeConfigurationFinished(StateType *state)
void notifyOnStateExited(StateType *state)
void notifyOnStateEntryEnd(StateType *state)
const SmaccStateMachineInfo & getStateMachineInfo()
void notifyOnStateExiting(StateType *state)
void notifyOnRuntimeConfigured(StateType *state)
void postEvent(EventType *ev, EventLifeTime evlifetime=EventLifeTime::ABSOLUTE)
void notifyOnStateEntryStart(StateType *state)
std::shared_ptr< rclcpp::Logger > logger_
rclcpp::Logger getLogger()
std::shared_ptr< TBehavior > configure(Args &&... args)
rclcpp::Node::SharedPtr node_
ISmaccState * parentState_
bool initializationFailed() const
const smacc2::introspection::SmaccStateInfo * stateInfo_
base_type::outermost_context_base_type outermost_context_base_type
static inner_context_ptr_type shallow_construct(const context_ptr_type &pContext, outermost_context_base_type &outermostContextBase)
ISmaccStateMachine & getStateMachine() override
static std::shared_ptr< smacc2::introspection::StateReactorHandler > static_createStateReactor(TArgs... args)
static void initial_deep_construct(outermost_context_base_type &outermostContextBase)
InnerInitial * smacc_inner_type
void checkWhileLoopConditionAndThrowEvent(bool(MostDerived::*conditionFn)())
static void configure_orthogonal_internal(std::function< void(ISmaccState *state)> initializationFunction)
static std::shared_ptr< smacc2::introspection::EventGeneratorHandler > static_createEventGenerator(TUArgs... args)
static std::shared_ptr< smacc2::introspection::StateReactorHandler > static_createStateReactor_aux(TUArgs... args)
void onInitializationFailure(const std::string &what)
const smacc2::introspection::SmaccStateInfo * getStateInfo()
sc::simple_state< MostDerived, Context, InnerInitial, historyMode > base_type
base_type::inner_initial_list inner_initial_list
bool getGlobalSMData(const std::string &name, T &ret)
static void deep_construct(const context_ptr_type &pContext, outermost_context_base_type &outermostContextBase)
virtual ISmaccState * getParentState()
SmaccState(my_context ctx)
base_type::context_ptr_type context_ptr_type
std::string getName() override
base_type::inner_context_ptr_type inner_context_ptr_type
static void configure_orthogonal_runtime(std::function< void(TBehavior &bh)> initializationFunction)
void setGlobalSMData(const std::string &name, T value)
static void configure_orthogonal_runtime(std::function< void(TBehavior &bh, MostDerived &)> initializationFunction)
static void configure_orthogonal(Args &&... args)
context_type::state_iterator state_iterator
Context::inner_context_type context_type
static std::map< const std::type_info *, std::vector< std::shared_ptr< SmaccStateReactorInfo > > > stateReactorsInfo
static std::map< const std::type_info *, std::vector< std::shared_ptr< SmaccEventGeneratorInfo > > > eventGeneratorsInfo
static std::map< const std::type_info *, std::vector< ClientBehaviorInfoEntry > > staticBehaviorInfo
std::map< std::string, std::shared_ptr< SmaccStateInfo > > states
static TypeInfo::Ptr getTypeInfoFromType()
rclcpp::Node::SharedPtr globalNh_
std::string demangleSymbol()
std::string cleanShortTypeName()
Definition common.hpp:69
void postStInitializationFailure(ISmaccStateMachine *stateMachine, const std::string &stateName, const std::string &what)
boost::intrusive_ptr< EventType > makeEvent(Args &&... args)
void standardOnExit(TState &st, std::true_type)
#define STATE_NAME
my_context(typename base_type::context_ptr_type pContext)
base_type::context_ptr_type pContext_
std::function< void(smacc2::ISmaccState *)> factoryFunction
smacc2_state_onExit_end
smacc2_state_onRuntimeConfigure_start
smacc2_state_onEntry_end
smacc2_state_onRuntimeConfigure_end
smacc2_state_onEntry_start
smacc2_state_onExit_start