SMACC2
Loading...
Searching...
No Matches
smacc_state_machine_impl.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
22
23#include <boost/intrusive_ptr.hpp>
24#include <memory>
25#include <sstream>
26#include <string>
27
36
37#include <boost/function_types/function_arity.hpp>
38#include <boost/function_types/function_type.hpp>
39#include <boost/function_types/parameter_types.hpp>
41#include <smacc2_msgs/msg/smacc_status.hpp>
42
43namespace smacc2
44{
45using namespace smacc2::introspection;
46
47template <typename TOrthogonal>
49{
50 std::lock_guard<std::recursive_mutex> lock(m_mutex_);
51
52 std::string orthogonalkey = demangledTypeName<TOrthogonal>();
53 TOrthogonal * ret = nullptr;
54
55 auto it = orthogonals_.find(orthogonalkey);
56
57 if (it != orthogonals_.end())
58 {
59 RCLCPP_DEBUG(
60 getLogger(),
61 "Orthogonal %s resource is being required from some state, client or component. Found "
62 "resource in "
63 "cache.",
64 orthogonalkey.c_str());
65 ret = dynamic_cast<TOrthogonal *>(it->second.get());
66 return ret;
67 }
68 else
69 {
70 std::stringstream ss;
71 ss << "Orthogonal not found " << orthogonalkey << std::endl;
72 ss << "The existing orthogonals are the following: " << std::endl;
73 for (const auto & orthogonal : orthogonals_)
74 {
75 ss << " - " << orthogonal.first << std::endl;
76 }
77
78 RCLCPP_WARN_STREAM(getLogger(), ss.str());
79
80 return nullptr;
81 }
82}
83
84//-------------------------------------------------------------------------------------------------------
85template <typename TOrthogonal>
87{
88 std::lock_guard<std::recursive_mutex> guard(m_mutex_);
89
90 std::string orthogonalkey = demangledTypeName<TOrthogonal>();
91
92 if (orthogonals_.count(orthogonalkey) == 0)
93 {
94 auto ret = std::make_shared<TOrthogonal>();
95 orthogonals_[orthogonalkey] = dynamic_pointer_cast<smacc2::ISmaccOrthogonal>(ret);
96
97 ret->setStateMachine(this);
98
99 RCLCPP_INFO(getLogger(), "%s Orthogonal is created", orthogonalkey.c_str());
100 }
101 else
102 {
103 RCLCPP_WARN_STREAM(
104 getLogger(), "There were already one existing orthogonal of type "
105 << orthogonalkey.c_str() << ". Skipping creation orthogonal request. ");
106 std::stringstream ss;
107 ss << "The existing orthogonals are the following: " << std::endl;
108 for (const auto & orthogonal : orthogonals_)
109 {
110 ss << " - " << orthogonal.first << std::endl;
111 }
112 RCLCPP_WARN_STREAM(getLogger(), ss.str());
113 }
114}
115
116//-------------------------------------------------------------------------------------------------------
117template <typename SmaccComponentType>
119 SmaccComponentType *& storage, ComponentRequirement requirementType, ISmaccOrthogonal * first)
120{
121 bool throwsException = requirementType == ComponentRequirement::HARD;
122 RCLCPP_DEBUG(
123 getLogger(), "component %s is required",
124 demangleSymbol(typeid(SmaccComponentType).name()).c_str());
125 std::lock_guard<std::recursive_mutex> lock(m_mutex_);
126
127 if (first != nullptr)
128 {
129 for (auto & client : first->clients_)
130 {
131 storage = client->getComponent<SmaccComponentType>();
132 if (storage != nullptr)
133 {
134 return;
135 }
136 }
137 }
138
139 for (auto ortho : this->orthogonals_)
140 {
141 for (auto & client : ortho.second->clients_)
142 {
143 storage = client->getComponent<SmaccComponentType>();
144 if (storage != nullptr)
145 {
146 return;
147 }
148 }
149 }
150
151 RCLCPP_WARN(
152 getLogger(), "component %s is required but it was not found in any orthogonal",
153 demangleSymbol(typeid(SmaccComponentType).name()).c_str());
154
155 if (throwsException)
156 throw std::runtime_error("component is required but it was not found in any orthogonal");
157}
158//-------------------------------------------------------------------------------------------------------
159template <typename SmaccComponentType>
161 const std::string & name, SmaccComponentType *& storage, ComponentRequirement requirementType,
162 ISmaccOrthogonal * first)
163{
164 bool throwsException = requirementType == ComponentRequirement::HARD;
165 RCLCPP_DEBUG(
166 getLogger(), "component %s (named '%s') is required",
167 demangleSymbol(typeid(SmaccComponentType).name()).c_str(), name.c_str());
168 std::lock_guard<std::recursive_mutex> lock(m_mutex_);
169
170 if (first != nullptr)
171 {
172 for (auto & client : first->clients_)
173 {
174 storage = client->getComponent<SmaccComponentType>(name);
175 if (storage != nullptr)
176 {
177 return;
178 }
179 }
180 }
181
182 for (auto ortho : this->orthogonals_)
183 {
184 for (auto & client : ortho.second->clients_)
185 {
186 storage = client->getComponent<SmaccComponentType>(name);
187 if (storage != nullptr)
188 {
189 return;
190 }
191 }
192 }
193
194 RCLCPP_WARN(
195 getLogger(), "component %s (named '%s') is required but it was not found in any orthogonal",
196 demangleSymbol(typeid(SmaccComponentType).name()).c_str(), name.c_str());
197
198 if (throwsException)
199 throw std::runtime_error("named component is required but it was not found in any orthogonal");
200}
201//-------------------------------------------------------------------------------------------------------
202template <typename EventType>
203void ISmaccStateMachine::postEvent(EventType * ev, EventLifeTime evlifetime)
204{
205 // Own the event from here on so the discard return and any exception in the overload below free it.
206 this->postEvent(boost::intrusive_ptr<EventType>(ev), evlifetime);
207}
208
209template <typename EventType>
211 const boost::intrusive_ptr<EventType> & evHolder, EventLifeTime evlifetime)
212{
213 std::lock_guard<std::recursive_mutex> guard(eventQueueMutex_);
214
215 // The refcount lives inside the event, so the scheduler's intrusive_ptr created later in
216 // SignalDetector::postEvent shares ownership with evHolder.
217 EventType * ev = evHolder.get();
218
219#define eventtypename demangleSymbol<EventType>().c_str()
220
221 TRACETOOLS_TRACEPOINT(smacc2_event, eventtypename);
222
223 {
225 EventLabel<EventType>(evinfo.label);
226
227 smacc2_msgs::msg::SmaccEvent event;
228 event.event_type = evinfo.getEventTypeName();
229 event.event_source = evinfo.getEventSourceName();
230 event.event_object_tag = evinfo.getOrthogonalName();
231 event.label = evinfo.label;
232
233 if (this->eventsLogPub_)
234 {
235 this->eventsLogPub_->publish(event);
236 }
237 }
238
239 if (
240 evlifetime == EventLifeTime::CURRENT_STATE &&
243 {
244 RCLCPP_WARN_STREAM(
245 getLogger(),
246 "[ISmaccStateMachine] CURRENT STATE SCOPED EVENT DISCARDED, state is exiting/transitioning "
247 << eventtypename);
248 return;
249 // in this case we may lose/skip events, if this is not right for some cases we should create a
250 // queue to lock the events during the transitions. This issues appeared when a client
251 // asyncbehavior was posting an event meanwhile we were doing the transition, but the main
252 // thread was waiting for its correct finalization (with thread.join)
253 }
254
255 // when a postting event is requested by any component, client, or client behavior
256 // we reach this place. Now, we propagate the events to all the state state reactors to generate
257 // some more events
258
259 RCLCPP_DEBUG_STREAM(getLogger(), "[PostEvent entry point] " << eventtypename);
260
261 if (reactorWalkDepth_ > 0)
262 {
263 // Posted by a reactor while its trigger is walked on the state machine thread: walk and
264 // queue in place, so the reactor's output stays ahead of its trigger in the queue.
265 if (!currentState_.empty())
266 {
268 }
269 this->signalDetector_->postEvent(ev);
270 return;
271 }
272
273 // The walk reads currentState_ and the reactors, which only the state machine thread writes,
274 // so it runs there as a scheduler work item that queues the trigger once the reactors ran.
276 [this, evHolder]()
277 {
279 if (!currentState_.empty())
280 {
281 propagateEventToStateReactors(currentState_.back(), evHolder.get());
282 }
284 this->signalDetector_->postEvent(evHolder.get());
285 });
286}
287
288template <typename EventType>
290{
292 RCLCPP_INFO_STREAM(getLogger(), "Event: " << evname);
293 this->postEvent(makeEvent<EventType>(), evlifetime);
294}
295
296template <typename T>
297bool ISmaccStateMachine::getGlobalSMData(const std::string & name, T & ret)
298{
299 std::lock_guard<std::recursive_mutex> lock(m_mutex_);
300 // RCLCPP_WARN(getLogger(),"get SM Data lock acquire");
301 bool success = false;
302
303 if (!globalData_.count(name))
304 {
305 // RCLCPP_WARN(getLogger(),"get SM Data - data do not exist");
306 success = false;
307 }
308 else
309 {
310 // RCLCPP_WARN(getLogger(),"get SM DAta -data exist. accessing");
311 try
312 {
313 auto & v = globalData_[name];
314
315 // RCLCPP_WARN(getLogger(),"get SM DAta -data exist. any cast");
316 ret = boost::any_cast<T>(v.second);
317 success = true;
318 // RCLCPP_WARN(getLogger(),"get SM DAta -data exist. success");
319 }
320 catch (boost::bad_any_cast & ex)
321 {
322 RCLCPP_ERROR(getLogger(), "bad any cast: %s", ex.what());
323 success = false;
324 }
325 }
326
327 // RCLCPP_WARN(getLogger(),"get SM Data lock release");
328 return success;
329}
330
331template <typename T>
332void ISmaccStateMachine::setGlobalSMData(const std::string & name, T value)
333{
334 {
335 std::lock_guard<std::recursive_mutex> lock(m_mutex_);
336 // RCLCPP_WARN(getLogger(),"set SM Data lock acquire");
337
338 globalData_[name] = {
339 [this, name]()
340 {
341 std::stringstream ss;
342 auto val = any_cast<T>(globalData_[name].second);
343 ss << val;
344 return ss.str();
345 },
346 value};
347 }
348
349 this->updateStatusMessage();
350}
351
352namespace utils
353{
354template <int arity>
355struct Bind
356{
357 template <typename TSmaccSignal, typename TMemberFunctionPrototype, typename TSmaccObjectType>
359 TSmaccSignal & signal, TMemberFunctionPrototype callback, TSmaccObjectType * object,
360 std::shared_ptr<CallbackCounterSemaphore> callbackCounter);
361};
362
363template <>
364struct Bind<1>
365{
366 template <typename TSmaccSignal, typename TMemberFunctionPrototype, typename TSmaccObjectType>
368 TSmaccSignal & signal, TMemberFunctionPrototype callback, TSmaccObjectType * object,
369 std::shared_ptr<CallbackCounterSemaphore> callbackCounter)
370 {
371 return signal.connect(
372
373 [=]()
374 {
375 if (callbackCounter == nullptr)
376 {
377 (object->*callback)();
378 }
379 else if (callbackCounter->acquire())
380 {
381 (object->*callback)();
382 callbackCounter->release();
383 }
384 });
385 }
386};
387
388template <>
389struct Bind<2>
390{
391 template <typename TSmaccSignal, typename TMemberFunctionPrototype, typename TSmaccObjectType>
393 TSmaccSignal & signal, TMemberFunctionPrototype callback, TSmaccObjectType * object,
394 std::shared_ptr<CallbackCounterSemaphore> callbackCounter)
395 {
396 return signal.connect(
397 [=](const auto & a1)
398 {
399 if (callbackCounter == nullptr)
400 {
401 return (object->*callback)(a1);
402 }
403 else if (callbackCounter->acquire())
404 {
405 (object->*callback)(a1);
406 callbackCounter->release();
407 }
408 });
409 }
410};
411
412template <>
413struct Bind<3>
414{
415 template <typename TSmaccSignal, typename TMemberFunctionPrototype, typename TSmaccObjectType>
417 TSmaccSignal & signal, TMemberFunctionPrototype callback, TSmaccObjectType * object,
418 std::shared_ptr<CallbackCounterSemaphore> callbackCounter)
419 {
420 return signal.connect(
421 [=](const auto & a1, const auto & a2)
422 {
423 if (callbackCounter == nullptr)
424 {
425 return (object->*callback)(a1, a2);
426 }
427 else if (callbackCounter->acquire())
428 {
429 (object->*callback)(a1, a2);
430 callbackCounter->release();
431 }
432 });
433 }
434};
435
436template <>
437struct Bind<4>
438{
439 template <typename TSmaccSignal, typename TMemberFunctionPrototype, typename TSmaccObjectType>
441 TSmaccSignal & signal, TMemberFunctionPrototype callback, TSmaccObjectType * object,
442 std::shared_ptr<CallbackCounterSemaphore> callbackCounter)
443 {
444 return signal.connect(
445 [=](const auto & a1, const auto & a2, const auto & a3)
446 {
447 if (callbackCounter == nullptr)
448 {
449 return (object->*callback)(a1, a2, a3);
450 }
451 else if (callbackCounter->acquire())
452 {
453 (object->*callback)(a1, a2, a3);
454 callbackCounter->release();
455 }
456 });
457 }
458};
459} // namespace utils
460using namespace smacc2::utils;
461
462template <typename TSmaccSignal, typename TMemberFunctionPrototype, typename TSmaccObjectType>
464 TSmaccSignal & signal, TMemberFunctionPrototype callback, TSmaccObjectType * object)
465{
466 std::lock_guard<std::recursive_mutex> lock(m_mutex_);
467
468 static_assert(
469 std::is_base_of<ISmaccState, TSmaccObjectType>::value ||
470 std::is_base_of<ISmaccClient, TSmaccObjectType>::value ||
471 std::is_base_of<ISmaccClientBehavior, TSmaccObjectType>::value ||
472 std::is_base_of<StateReactor, TSmaccObjectType>::value ||
473 std::is_base_of<ISmaccComponent, TSmaccObjectType>::value,
474 "Only are accepted smacc types as subscribers for smacc signals");
475
476 typedef decltype(callback) ft;
479
480 // long life-time objects
481 if (
482 std::is_base_of<ISmaccComponent, TSmaccObjectType>::value ||
483 std::is_base_of<ISmaccClient, TSmaccObjectType>::value ||
484 std::is_base_of<ISmaccOrthogonal, TSmaccObjectType>::value ||
485 std::is_base_of<ISmaccStateMachine, TSmaccObjectType>::value)
486 {
487 RCLCPP_INFO(
488 getLogger(),
489 "[StateMachine] Long life-time SMACC signal subscription created. Subscriber is %s. Callback "
490 "is: %s",
492 demangleSymbol(typeid(callback).name()).c_str());
493
494 connection = binder.bindaux(signal, callback, object, nullptr);
495 }
496 else if (
497 std::is_base_of<ISmaccState, TSmaccObjectType>::value ||
498 std::is_base_of<StateReactor, TSmaccObjectType>::value ||
499 std::is_base_of<ISmaccClientBehavior, TSmaccObjectType>::value)
500 {
501 RCLCPP_INFO(
502 getLogger(),
503 "[StateMachine] Life-time constrained SMACC signal subscription created. Subscriber is %s",
505
506 std::shared_ptr<CallbackCounterSemaphore> callbackCounterSemaphore;
507 // Key on the complete object's address, not on whichever base pointer the subscriber
508 // happened to pass: disconnectSmaccSignalObject is called with a base-class pointer on
509 // dispose, and with multiple inheritance those addresses differ.
510 void * key = dynamic_cast<void *>(object);
511 if (stateCallbackConnections.count(key))
512 {
513 callbackCounterSemaphore = stateCallbackConnections[key];
514 }
515 else
516 {
517 callbackCounterSemaphore =
518 std::make_shared<CallbackCounterSemaphore>(demangledTypeName<TSmaccObjectType>().c_str());
519 stateCallbackConnections[key] = callbackCounterSemaphore;
520 }
521
522 connection = binder.bindaux(signal, callback, object, callbackCounterSemaphore);
523 callbackCounterSemaphore->addConnection(connection);
524 }
525 else // state life-time objects
526 {
527 RCLCPP_WARN(
528 getLogger(),
529 "[StateMachine] Connecting signal to an unknown object with unknown lifetime "
530 "behavior. An exception may occur if the object is destroyed during the execution.");
531
532 connection = binder.bindaux(signal, callback, object, nullptr);
533 }
534
535 return connection;
536}
537
538template <typename StateType>
540{
541 std::lock_guard<std::recursive_mutex> lock(m_mutex_);
542
543 RCLCPP_DEBUG(
544 getLogger(),
545 "[State Machine] Initializing a new state '%s' and updating current state. Getting state "
546 "meta-information. number of orthogonals: %ld",
547 demangleSymbol(typeid(StateType).name()).c_str(), this->orthogonals_.size());
548
550 currentState_.push_back(state);
551 currentStateInfo_ = stateMachineInfo_->getState<StateType>();
552}
553
554template <typename StateType>
556{
557 RCLCPP_INFO(
558 getLogger(), "[%s] State OnEntry code finished.",
559 demangleSymbol(typeid(StateType).name()).c_str());
560
561 auto currentState = this->currentState_.back();
562 // A state whose initialization failed starts nothing: no behavior, reactor or generator is entered.
563 const bool enter = !currentState->initializationFailed();
565 for (auto pair : this->orthogonals_)
566 {
567 if (!enter) break;
568 RCLCPP_DEBUG(getLogger(), "Orthogonal onEntry: %s.", pair.second->getName().c_str());
569 auto & orthogonal = pair.second;
570 try
571 {
572 orthogonal->onEntry();
573 }
574 catch (const std::exception & e)
575 {
576 RCLCPP_ERROR(
577 getLogger(),
578 "[Orthogonal %s] Exception on Entry - continuing with next orthogonal. Exception info: %s",
579 pair.second->getName().c_str(), e.what());
580 }
581 }
582
583 for (auto & sr : currentState->getStateReactors())
584 {
585 if (!enter) break;
586 const auto & reactor = *sr;
587 auto srname = smacc2::demangleSymbol(typeid(reactor).name());
588 RCLCPP_INFO_STREAM(getLogger(), "State reactor onEntry: " << srname);
589 try
590 {
591 sr->onEntry();
592 }
593 catch (const std::exception & e)
594 {
595 RCLCPP_ERROR(
596 getLogger(),
597 "[State Reactor %s] Exception on Entry - continuing with next state reactor. Exception "
598 "info: %s",
599 srname.c_str(), e.what());
600 }
601 }
602
603 for (auto & eg : currentState->getEventGenerators())
604 {
605 if (!enter) break;
606 const auto & generator = *eg;
607 auto egname = smacc2::demangleSymbol(typeid(generator).name());
608 RCLCPP_INFO_STREAM(getLogger(), "Event generator onEntry: " << egname);
609 try
610 {
611 eg->onEntry();
612 }
613 catch (const std::exception & e)
614 {
615 RCLCPP_ERROR(
616 getLogger(),
617 "[Event generator %s] Exception on Entry - continuing with next state reactor. Exception "
618 "info: %s",
619 egname.c_str(), e.what());
620 }
621 }
622
623 {
624 std::lock_guard<std::recursive_mutex> lock(m_mutex_);
625 this->updateStatusMessage();
627 }
628}
629
630template <typename StateType>
632{
633 for (auto pair : this->orthogonals_)
634 {
635 // The behaviors of a state whose runtimeConfigure threw are not configured.
636 if (state->initializationFailed()) break;
637 // RCLCPP_INFO(getLogger(),"ortho onruntime configure: %s", pair.second->getName().c_str());
638 auto & orthogonal = pair.second;
639 orthogonal->runtimeConfigure();
640 }
641
642 {
643 std::lock_guard<std::recursive_mutex> lock(m_mutex_);
644 this->updateStatusMessage();
646
648 }
649}
650
651template <typename StateType>
656
657template <typename StateType>
659{
661 auto fullname = demangleSymbol(typeid(StateType).name());
662 RCLCPP_WARN_STREAM(getLogger(), "Exiting state: " << fullname);
663
664 RCLCPP_INFO_STREAM(getLogger(), "Notification state exit: leaving state " << state);
665 // Nothing was entered in a state whose initialization failed, so nothing is exited.
666 if (state->initializationFailed()) return;
667 for (auto pair : this->orthogonals_)
668 {
669 auto & orthogonal = pair.second;
670 try
671 {
672 orthogonal->onExit();
673 }
674 catch (const std::exception & e)
675 {
676 RCLCPP_ERROR(
677 getLogger(),
678 "[Orthogonal %s] Exception onExit - continuing with next orthogonal. Exception info: %s",
679 pair.second->getName().c_str(), e.what());
680 }
681 }
682
683 for (auto & sr : state->getStateReactors())
684 {
685 auto srname = smacc2::demangleSymbol(typeid(*sr).name());
686 RCLCPP_INFO_STREAM(getLogger(), "State reactor OnExit: " << srname);
687 try
688 {
689 sr->onExit();
690 }
691 catch (const std::exception & e)
692 {
693 RCLCPP_ERROR(
694 getLogger(),
695 "[State Reactor %s] Exception on OnExit - continuing with next state reactor. Exception "
696 "info: %s",
697 srname.c_str(), e.what());
698 }
699 }
700
701 for (auto & eg : state->getEventGenerators())
702 {
703 auto egname = smacc2::demangleSymbol(typeid(*eg).name());
704 RCLCPP_INFO_STREAM(getLogger(), "Event generator OnExit: " << egname);
705 try
706 {
707 eg->onExit();
708 }
709 catch (const std::exception & e)
710 {
711 RCLCPP_ERROR(
712 getLogger(),
713 "[State Reactor %s] Exception on OnExit - continuing with next state reactor. Exception "
714 "info: %s",
715 egname.c_str(), e.what());
716 }
717 }
718}
719
720template <typename StateType>
722{
723 this->lockStateMachine("state exit");
724
726
727 auto fullname = demangleSymbol(typeid(StateType).name());
728 RCLCPP_WARN_STREAM(getLogger(), "Exiting state: " << fullname);
729
730 RCLCPP_INFO_STREAM(getLogger(), "Notification state disposing: leaving state" << state);
731 for (auto pair : this->orthogonals_)
732 {
733 auto & orthogonal = pair.second;
734 try
735 {
736 orthogonal->onDispose();
737 }
738 catch (const std::exception & e)
739 {
740 RCLCPP_ERROR(
741 getLogger(),
742 "[Orthogonal %s] Exception onDispose - continuing with next orthogonal. Exception info: %s",
743 pair.second->getName().c_str(), e.what());
744 }
745 }
746
747 for (auto & sr : state->getStateReactors())
748 {
749 // Keep the std::string alive for the whole iteration; taking c_str() of the temporary
750 // returned by demangleSymbol left a dangling pointer that the log lines below read.
751 auto srname = smacc2::demangleSymbol(typeid(*sr).name());
752 RCLCPP_INFO(getLogger(), "State reactor disposing: %s", srname.c_str());
753 try
754 {
755 this->disconnectSmaccSignalObject(sr.get());
756 }
757 catch (const std::exception & e)
758 {
759 RCLCPP_ERROR(
760 getLogger(),
761 "[State Reactor %s] Exception on OnDispose - continuing with next state reactor. Exception "
762 "info: %s",
763 srname.c_str(), e.what());
764 }
765 }
766
767 for (auto & eg : state->getEventGenerators())
768 {
769 auto egname = smacc2::demangleSymbol(typeid(*eg).name());
770 RCLCPP_INFO(getLogger(), "Event generator disposing: %s", egname.c_str());
771 try
772 {
773 this->disconnectSmaccSignalObject(eg.get());
774 }
775 catch (const std::exception & e)
776 {
777 RCLCPP_ERROR(
778 getLogger(),
779 "[Event Generator %s] Exception on OnDispose - continuing with next event generator. "
780 "Exception info: %s",
781 egname.c_str(), e.what());
782 }
783 }
784
785 // The state itself may have subscribed to signals with `this`. Boost.Statechart destroys
786 // the state object right after exit() returns, so its entry must be finalized here, and
787 // last: behaviors, reactors and generators are disposed above, and a behavior's onExit
788 // thread may still emit a signal the state subscribed to. finalize() waits for in-flight
789 // callbacks while m_mutex_ is held (same as the behavior path in orthogonal.cpp).
790 this->disconnectSmaccSignalObject(state);
791
792 // NOTE: do NOT clear stateCallbackConnections here. Entries are erased
793 // per-object by disconnectSmaccSignalObject when each owner is disposed
794 // (behaviors via orthogonal onDispose, state reactors, event generators and
795 // the state itself above). A blanket clear also dropped - without finalizing -
796 // the entries of container-state behaviors that outlive this inner state exit,
797 // so their boost connections were never disconnected and the next signal
798 // emission invoked a callback on a destroyed object (use-after-free segfault).
799 currentState_.pop_back();
800
801 // then call exit state
802 RCLCPP_WARN_STREAM(getLogger(), "State exit: " << fullname);
803
805 this->unlockStateMachine("state exit");
806}
807//------------------------------------------------------------------------------------------------
808template <typename EventType>
810{
811 RCLCPP_DEBUG(
812 getLogger(), "PROPAGATING EVENT [%s] TO SRs [%s]: ", demangleSymbol<EventType>().c_str(),
813 st->getClassName().c_str());
814 for (auto & sb : st->getStateReactors())
815 {
816 // A throwing reactor must not end the state machine thread; log it and go on to the next.
817 const auto & reactor = *sb;
818 try
819 {
820 sb->notifyEvent(ev);
821 }
822 catch (const std::exception & e)
823 {
824 RCLCPP_ERROR(
825 getLogger(), "[%s] state reactor threw on event %s: %s",
826 demangleType(typeid(reactor)).c_str(), demangleSymbol<EventType>().c_str(), e.what());
827 }
828 catch (...)
829 {
830 RCLCPP_ERROR(
831 getLogger(), "[%s] state reactor threw a non-standard exception on event %s",
832 demangleType(typeid(reactor)).c_str(), demangleSymbol<EventType>().c_str());
833 }
834 }
835
836 auto * pst = st->getParentState();
837 if (pst != nullptr)
838 {
840 }
841}
842
843template <typename InitialStateType>
845{
846 this->stateMachineInfo_ = std::make_shared<SmaccStateMachineInfo>(this->getNode());
847 this->stateMachineInfo_->buildStateMachineInfo<InitialStateType>();
848 this->stateMachineInfo_->assembleSMStructureMessage(this);
850}
851
853
855
860
861} // namespace smacc2
std::vector< std::shared_ptr< smacc2::ISmaccClient > > clients_
std::map< std::string, std::shared_ptr< smacc2::ISmaccOrthogonal > > orthogonals_
void setGlobalSMData(const std::string &name, T value)
std::vector< ISmaccState * > currentState_
std::recursive_mutex eventQueueMutex_
std::shared_ptr< SmaccStateInfo > currentStateInfo_
rclcpp::Node::SharedPtr getNode()
std::map< std::string, std::pair< std::function< std::string()>, boost::any > > globalData_
std::atomic< StateMachineInternalAction > stateMachineCurrentAction
void notifyOnRuntimeConfigurationFinished(StateType *state)
void disconnectSmaccSignalObject(void *object_ptr)
smacc2::SmaccSignalConnection createSignalConnection(TSmaccSignal &signal, TMemberFunctionPrototype callback, TSmaccObjectType *object)
bool getGlobalSMData(const std::string &name, T &ret)
void notifyOnStateExited(StateType *state)
void notifyOnStateEntryEnd(StateType *state)
void propagateEventToStateReactors(ISmaccState *st, EventType *ev)
const SmaccStateMachineInfo & getStateMachineInfo()
static thread_local int reactorWalkDepth_
void unlockStateMachine(const std::string &msg)
void notifyOnStateExiting(StateType *state)
std::map< void *, std::shared_ptr< CallbackCounterSemaphore > > stateCallbackConnections
void lockStateMachine(const std::string &msg)
void notifyOnRuntimeConfigured(StateType *state)
void requiresComponent(SmaccComponentType *&storage, ComponentRequirement requirementType, ISmaccOrthogonal *first=nullptr)
std::shared_ptr< SmaccStateMachineInfo > stateMachineInfo_
void postEvent(EventType *ev, EventLifeTime evlifetime=EventLifeTime::ABSOLUTE)
rclcpp::Publisher< smacc2_msgs::msg::SmaccEvent >::SharedPtr eventsLogPub_
void notifyOnStateEntryStart(StateType *state)
ISmaccState * getParentState()
virtual std::string getClassName()
std::vector< std::shared_ptr< StateReactor > > & getStateReactors()
void queueWorkItem(const SmaccFifoWorker::work_item &item)
void notifyStateExited(ISmaccState *currentState)
void notifyStateConfigured(ISmaccState *currentState)
static TypeInfo::Ptr getTypeInfoFromType()
std::enable_if< HasEventLabel< T >::value, void >::type EventLabel(std::string &label)
std::string demangleSymbol()
std::string demangledTypeName()
std::string demangleType(const std::type_info *tinfo)
boost::signals2::connection SmaccSignalConnection
boost::intrusive_ptr< EventType > makeEvent(Args &&... args)
ComponentRequirement
Definition common.hpp:82
#define eventtypename
smacc2::SmaccSignalConnection bindaux(TSmaccSignal &signal, TMemberFunctionPrototype callback, TSmaccObjectType *object, std::shared_ptr< CallbackCounterSemaphore > callbackCounter)
smacc2::SmaccSignalConnection bindaux(TSmaccSignal &signal, TMemberFunctionPrototype callback, TSmaccObjectType *object, std::shared_ptr< CallbackCounterSemaphore > callbackCounter)
smacc2::SmaccSignalConnection bindaux(TSmaccSignal &signal, TMemberFunctionPrototype callback, TSmaccObjectType *object, std::shared_ptr< CallbackCounterSemaphore > callbackCounter)
smacc2::SmaccSignalConnection bindaux(TSmaccSignal &signal, TMemberFunctionPrototype callback, TSmaccObjectType *object, std::shared_ptr< CallbackCounterSemaphore > callbackCounter)
smacc2::SmaccSignalConnection bindaux(TSmaccSignal &signal, TMemberFunctionPrototype callback, TSmaccObjectType *object, std::shared_ptr< CallbackCounterSemaphore > callbackCounter)
smacc2_event