SMACC2
Loading...
Searching...
No Matches
smacc2::ISmaccStateMachine Class Reference

#include <smacc_state_machine.hpp>

Inheritance diagram for smacc2::ISmaccStateMachine:
Inheritance graph
Collaboration diagram for smacc2::ISmaccStateMachine:
Collaboration graph

Public Member Functions

 ISmaccStateMachine (std::string stateMachineName, SignalDetector *signalDetector, const rclcpp::NodeOptions &nodeOptions=rclcpp::NodeOptions())
 
virtual ~ISmaccStateMachine ()
 
 ISmaccStateMachine (const ISmaccStateMachine &)=delete
 
ISmaccStateMachine & operator= (const ISmaccStateMachine &)=delete
 
 ISmaccStateMachine (ISmaccStateMachine &&)=delete
 
ISmaccStateMachine & operator= (ISmaccStateMachine &&)=delete
 
virtual void reset ()
 
virtual void stop ()
 
virtual void eStop ()
 
void joinAsyncClientBehaviorThreads ()
 
template<typename TOrthogonal >
TOrthogonal * getOrthogonal ()
 
template<typename TOrthogonal , typename TClientBehavior >
TClientBehavior * getClientBehavior (int index=0)
 
const std::map< std::string, std::shared_ptr< smacc2::ISmaccOrthogonal > > & getOrthogonals () const
 
template<typename SmaccComponentType >
void requiresComponent (SmaccComponentType *&storage, ComponentRequirement requirementType, ISmaccOrthogonal *first=nullptr)
 
template<typename SmaccComponentType >
void requiresComponent (const std::string &name, SmaccComponentType *&storage, ComponentRequirement requirementType, ISmaccOrthogonal *first=nullptr)
 
template<typename EventType >
void postEvent (EventType *ev, EventLifeTime evlifetime=EventLifeTime::ABSOLUTE)
 
template<typename EventType >
void postEvent (const boost::intrusive_ptr< EventType > &evHolder, EventLifeTime evlifetime=EventLifeTime::ABSOLUTE)
 
template<typename EventType >
void postEvent (EventLifeTime evlifetime=EventLifeTime::ABSOLUTE)
 
template<typename T >
bool getGlobalSMData (const std::string &name, T &ret)
 
template<typename T >
void setGlobalSMData (const std::string &name, T value)
 
std::string getStateMachineName ()
 
void state_machine_visualization ()
 
std::shared_ptr< SmaccStateInfo > getCurrentStateInfo ()
 
void publishTransition (const SmaccTransitionInfo &transitionInfo)
 
virtual void onInitialize ()
 this function should be implemented by the user to create the orthogonals
 
virtual void onUnhandledStInitializationFailure (const std::string &stateName, const std::string &what)
 
void getTransitionLogHistory (const std::shared_ptr< rmw_request_id_t > request_header, const std::shared_ptr< smacc2_msgs::srv::SmaccGetTransitionHistory::Request > req, std::shared_ptr< smacc2_msgs::srv::SmaccGetTransitionHistory::Response > res)
 
template<typename TSmaccSignal , typename TMemberFunctionPrototype , typename TSmaccObjectType >
smacc2::SmaccSignalConnection createSignalConnection (TSmaccSignal &signal, TMemberFunctionPrototype callback, TSmaccObjectType *object)
 
void disconnectSmaccSignalObject (void *object_ptr)
 
template<typename T >
std::enable_if_t< std::is_polymorphic< T >::value > disconnectSmaccSignalObject (T *object)
 
template<typename StateType >
void notifyOnStateEntryStart (StateType *state)
 
template<typename StateType >
void notifyOnStateEntryEnd (StateType *state)
 
template<typename StateType >
void notifyOnRuntimeConfigured (StateType *state)
 
template<typename StateType >
void notifyOnStateExiting (StateType *state)
 
template<typename StateType >
void notifyOnStateExited (StateType *state)
 
template<typename StateType >
void notifyOnRuntimeConfigurationFinished (StateType *state)
 
int64_t getCurrentStateCounter () const
 
ISmaccState * getCurrentState () const
 
const SmaccStateMachineInfo & getStateMachineInfo ()
 
template<typename InitialStateType >
void buildStateMachineInfo ()
 
rclcpp::Node::SharedPtr getNode ()
 
rclcpp::Logger getLogger ()
 
std::recursive_mutex & getMutex ()
 

Protected Member Functions

void checkStateMachineConsistence ()
 
void initializeROS (const std::string &shortname)
 
void onInitialized ()
 
template<typename TOrthogonal >
void createOrthogonal ()
 

Protected Attributes

rclcpp::Node::SharedPtr nh_
 
rclcpp::TimerBase::SharedPtr timer_
 
rclcpp::Publisher< smacc2_msgs::msg::SmaccStateMachine >::SharedPtr stateMachinePub_
 
rclcpp::Publisher< smacc2_msgs::msg::SmaccStatus >::SharedPtr stateMachineStatusPub_
 
rclcpp::Publisher< smacc2_msgs::msg::SmaccTransitionLogEntry >::SharedPtr transitionLogPub_
 
rclcpp::Publisher< smacc2_msgs::msg::SmaccEvent >::SharedPtr eventsLogPub_
 
rclcpp::Service< smacc2_msgs::srv::SmaccGetTransitionHistory >::SharedPtr transitionHistoryService_
 
std::vector< ISmaccState * > currentState_
 
std::shared_ptr< SmaccStateInfo > currentStateInfo_
 
smacc2_msgs::msg::SmaccStatus status_msg_
 
std::map< std::string, std::shared_ptr< smacc2::ISmaccOrthogonal > > orthogonals_
 
std::shared_ptr< SmaccStateMachineInfo > stateMachineInfo_
 

Private Member Functions

void lockStateMachine (const std::string &msg)
 
void unlockStateMachine (const std::string &msg)
 
template<typename EventType >
void propagateEventToStateReactors (ISmaccState *st, EventType *ev)
 
void updateStatusMessage ()
 

Private Attributes

std::recursive_mutex m_mutex_
 
std::recursive_mutex eventQueueMutex_
 
std::atomic< StateMachineInternalAction > stateMachineCurrentAction
 
std::map< void *, std::shared_ptr< CallbackCounterSemaphore > > stateCallbackConnections
 
std::map< std::string, std::pair< std::function< std::string()>, boost::any > > globalData_
 
std::deque< smacc2_msgs::msg::SmaccTransitionLogEntry > transitionLogHistory_
 
std::mutex transitionLogMutex_
 
size_t transitionLogHistorySize_ = 1000
 
smacc2::SMRunMode runMode_
 
SignalDetector * signalDetector_
 
int64_t stateSeqCounter_ = 0
 

Static Private Attributes

static thread_local int reactorWalkDepth_ = 0
 

Friends

class ISmaccState
 
class SignalDetector
 

Detailed Description

Definition at line 67 of file smacc_state_machine.hpp.

Constructor & Destructor Documentation

◆ ISmaccStateMachine() [1/3]

smacc2::ISmaccStateMachine::ISmaccStateMachine ( std::string stateMachineName,
SignalDetector * signalDetector,
const rclcpp::NodeOptions & nodeOptions = rclcpp::NodeOptions() )

Definition at line 38 of file smacc_state_machine.cpp.

41: nh_(rclcpp::Node::make_shared(stateMachineName, nodeOptions))
42{
43 RCLCPP_INFO_STREAM(
44 nh_->get_logger(), "Creating state machine base: " << nh_->get_fully_qualified_name());
45
46 signalDetector_ = signalDetector;
48
49 std::string runMode;
50 if (nh_->get_parameter("run_mode", runMode))
51 {
52 if (runMode == "debug")
53 {
55 }
56 else if (runMode == "release")
57 {
59 }
60 else
61 {
62 RCLCPP_ERROR(nh_->get_logger(), "Incorrect run_mode value: %s", runMode.c_str());
63 }
64 }
65 else
66 {
68 }
69}
void initialize(ISmaccStateMachine *stateMachine)

References smacc2::DEBUG, smacc2::SignalDetector::initialize(), nh_, smacc2::RELEASE, runMode_, and signalDetector_.

Here is the call graph for this function:

◆ ~ISmaccStateMachine()

smacc2::ISmaccStateMachine::~ISmaccStateMachine ( )
virtual

Definition at line 71 of file smacc_state_machine.cpp.

72{
73 RCLCPP_INFO(nh_->get_logger(), "Finishing State Machine");
74
75 // initiate_impl stored this state machine's node in the static introspection::globalNh_ for the
76 // type walker's logging. Release it here so that nh_, destroyed with the other members below,
77 // is the node's last owner and the node is finalized inside run<>, while the rclcpp context is
78 // still valid. Left in the static, the node would be destroyed by the exit handlers after
79 // rclcpp::shutdown() has finalized the DDS participant, which crashes in rcl_service_fini.
81}
rclcpp::Node::SharedPtr globalNh_

References smacc2::introspection::globalNh_, and nh_.

◆ ISmaccStateMachine() [2/3]

smacc2::ISmaccStateMachine::ISmaccStateMachine ( const ISmaccStateMachine & )
delete

◆ ISmaccStateMachine() [3/3]

smacc2::ISmaccStateMachine::ISmaccStateMachine ( ISmaccStateMachine && )
delete

Member Function Documentation

◆ buildStateMachineInfo()

template<typename InitialStateType >
void smacc2::ISmaccStateMachine::buildStateMachineInfo ( )

Definition at line 844 of file smacc_state_machine_impl.hpp.

845{
846 this->stateMachineInfo_ = std::make_shared<SmaccStateMachineInfo>(this->getNode());
847 this->stateMachineInfo_->buildStateMachineInfo<InitialStateType>();
848 this->stateMachineInfo_->assembleSMStructureMessage(this);
850}
rclcpp::Node::SharedPtr getNode()
std::shared_ptr< SmaccStateMachineInfo > stateMachineInfo_

References checkStateMachineConsistence(), getNode(), and stateMachineInfo_.

Referenced by smacc2::SmaccStateMachineBase< DerivedStateMachine, InitialStateType >::initiate_impl().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ checkStateMachineConsistence()

void smacc2::ISmaccStateMachine::checkStateMachineConsistence ( )
protected

Definition at line 287 of file smacc_state_machine.cpp.

287{}

Referenced by buildStateMachineInfo().

Here is the caller graph for this function:

◆ createOrthogonal()

template<typename TOrthogonal >
void smacc2::ISmaccStateMachine::createOrthogonal ( )
protected

Definition at line 86 of file smacc_state_machine_impl.hpp.

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}
std::map< std::string, std::shared_ptr< smacc2::ISmaccOrthogonal > > orthogonals_
std::string demangledTypeName()

References smacc2::introspection::demangledTypeName(), getLogger(), m_mutex_, and orthogonals_.

Here is the call graph for this function:

◆ createSignalConnection()

template<typename TSmaccSignal , typename TMemberFunctionPrototype , typename TSmaccObjectType >
smacc2::SmaccSignalConnection smacc2::ISmaccStateMachine::createSignalConnection ( TSmaccSignal & signal,
TMemberFunctionPrototype callback,
TSmaccObjectType * object )

Definition at line 463 of file smacc_state_machine_impl.hpp.

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;
477 Bind<boost::function_types::function_arity<ft>::value> binder;
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}
std::map< void *, std::shared_ptr< CallbackCounterSemaphore > > stateCallbackConnections
std::string demangleSymbol()
boost::signals2::connection SmaccSignalConnection

References smacc2::introspection::demangledTypeName(), smacc2::introspection::demangleSymbol(), getLogger(), m_mutex_, and stateCallbackConnections.

Referenced by smacc2::ISmaccClient::connectSignal(), smacc2::client_bases::SmaccActionClientBase< ActionType >::onAborted(), smacc2::client_bases::SmaccActionClientBase< ActionType >::onAborted(), smacc2::client_core_components::CpActionClient< ActionType >::onAborted(), cl_gcalcli::CpCalendarPoller::onAgendaUpdated(), cl_isaac_apriltag::CpAprilTagTracker::onAprilTagDetected(), cl_keyboard::components::CpKeyboardListener1::OnArrowPress(), cl_gcalcli::CpGcalcliConnection::onAuthenticationRequired(), cl_nav2z::CpBondListener::onBondMessage(), smacc2::client_bases::SmaccActionClientBase< ActionType >::onCancelled(), smacc2::client_bases::SmaccActionClientBase< ActionType >::onCancelled(), smacc2::client_core_components::CpActionClient< ActionType >::onCancelled(), smacc2::client_core_components::CpSubprocessExecutor::onCommandCompleted(), smacc2::client_core_components::CpSubprocessExecutor::onCommandFailed(), cl_modbus_tcp_relay::CpModbusConnection::onConnectionError(), cl_gcalcli::CpGcalcliConnection::onConnectionLost(), cl_modbus_tcp_relay::CpModbusConnection::onConnectionLost(), cl_gcalcli::CpGcalcliConnection::onConnectionRestored(), cl_modbus_tcp_relay::CpModbusConnection::onConnectionRestored(), cl_gcalcli::CpCalendarEventListener::onEventDetected(), cl_gcalcli::CpCalendarEventListener::onEventEnded(), cl_gcalcli::CpCalendarEventListener::onEventStarted(), smacc2::client_core_components::CpServiceClient< ServiceType >::onFailure(), smacc2::SmaccAsyncClientBehavior::onFailure(), smacc2::client_core_components::CpActionClient< ActionType >::onFeedback(), smacc2::SmaccAsyncClientBehavior::onFinished(), smacc2::client_bases::SmaccSubscriberClient< MessageType >::onFirstMessageReceived(), smacc2::client_core_components::CpTopicSubscriber< MessageType >::onFirstMessageReceived(), cl_keyboard::components::CpKeyboardListener1::OnKeyPress(), smacc2::client_bases::SmaccSubscriberClient< MessageType >::onMessageReceived(), smacc2::client_core_components::CpTopicSubscriber< MessageType >::onMessageReceived(), cl_generic_sensor::components::CpMessageTimeout< MessageType >::onMessageTimeout(), cl_moveit2z::CpMoveGroupInterface::onMotionExecutionFailed(), cl_moveit2z::CpMoveGroupInterface::onMotionExecutionSucceeded(), cl_nav2z::components::CpNav2ActionInterface::onNavigationAborted(), cl_nav2z::components::CpNav2ActionInterface::onNavigationCancelled(), cl_nav2z::components::CpNav2ActionInterface::onNavigationFeedback(), cl_nav2z::components::CpNav2ActionInterface::onNavigationSucceeded(), cl_px4_mr::CpForwardObstacleGuard::onObstacleCleared(), cl_px4_mr::CpForwardObstacleGuard::onObstacleTooClose(), cl_modbus_tcp_relay::CpModbusRelay::onReadComplete(), smacc2::client_core_components::CpServiceClient< ServiceType >::onRequestSent(), smacc2::client_core_components::CpServiceClient< ServiceType >::onResponse(), smacc2::client_bases::SmaccServiceServerClient< TService >::onServiceRequestReceived(), smacc2::client_bases::SmaccActionClientBase< ActionType >::onSucceeded(), smacc2::client_bases::SmaccActionClientBase< ActionType >::onSucceeded(), smacc2::client_core_components::CpActionClient< ActionType >::onSucceeded(), smacc2::SmaccAsyncClientBehavior::onSuccess(), cl_ros2_timer::CbTimerCountdownLoop::onTimerTick(), cl_ros2_timer::CbTimerCountdownOnce::onTimerTick(), smacc2::client_core_components::CpRos2Timer::onTimerTick(), cl_lifecycle_node::CpLifecycleEventMonitor::onTransitionActivate(), cl_lifecycle_node::CpLifecycleEventMonitor::onTransitionActiveShutdown(), cl_lifecycle_node::CpLifecycleEventMonitor::onTransitionCleanup(), cl_lifecycle_node::CpLifecycleEventMonitor::onTransitionConfigure(), cl_lifecycle_node::CpLifecycleEventMonitor::onTransitionCreate(), cl_lifecycle_node::CpLifecycleEventMonitor::onTransitionDeactivate(), cl_lifecycle_node::CpLifecycleEventMonitor::onTransitionDestroy(), cl_lifecycle_node::CpLifecycleEventMonitor::onTransitionInactiveShutdown(), cl_lifecycle_node::CpLifecycleEventMonitor::onTransitionOnActivateError(), cl_lifecycle_node::CpLifecycleEventMonitor::onTransitionOnActivateFailure(), cl_lifecycle_node::CpLifecycleEventMonitor::onTransitionOnActivateSuccess(), cl_lifecycle_node::CpLifecycleEventMonitor::onTransitionOnActiveShutdownError(), cl_lifecycle_node::CpLifecycleEventMonitor::onTransitionOnActiveShutdownFailure(), cl_lifecycle_node::CpLifecycleEventMonitor::onTransitionOnActiveShutdownSuccess(), cl_lifecycle_node::CpLifecycleEventMonitor::onTransitionOnCleanupError(), cl_lifecycle_node::CpLifecycleEventMonitor::onTransitionOnCleanupFailure(), cl_lifecycle_node::CpLifecycleEventMonitor::onTransitionOnCleanupSuccess(), cl_lifecycle_node::CpLifecycleEventMonitor::onTransitionOnConfigureError(), cl_lifecycle_node::CpLifecycleEventMonitor::onTransitionOnConfigureFailure(), cl_lifecycle_node::CpLifecycleEventMonitor::onTransitionOnConfigureSuccess(), cl_lifecycle_node::CpLifecycleEventMonitor::onTransitionOnDeactivateError(), cl_lifecycle_node::CpLifecycleEventMonitor::onTransitionOnDeactivateFailure(), cl_lifecycle_node::CpLifecycleEventMonitor::onTransitionOnDeactivateSuccess(), cl_lifecycle_node::CpLifecycleEventMonitor::onTransitionOnErrorError(), cl_lifecycle_node::CpLifecycleEventMonitor::onTransitionOnErrorFailure(), cl_lifecycle_node::CpLifecycleEventMonitor::onTransitionOnErrorSuccess(), cl_lifecycle_node::CpLifecycleEventMonitor::onTransitionOnShutdownError(), cl_lifecycle_node::CpLifecycleEventMonitor::onTransitionOnShutdownFailure(), cl_lifecycle_node::CpLifecycleEventMonitor::onTransitionOnShutdownSuccess(), cl_lifecycle_node::CpLifecycleEventMonitor::onTransitionUnconfiguredShutdown(), cl_modbus_tcp_relay::CpModbusRelay::onWriteFailure(), cl_modbus_tcp_relay::CpModbusRelay::onWriteSuccess(), cl_http::CbHttpRequestBase::runtimeConfigure(), smacc2::client_behaviors::CbWaitTopicMessage< TMessage >::runtimeConfigure(), cl_px4_mr::CbArmPX4::wireCompletionSignals(), cl_px4_mr::CbChangeAltitude::wireCompletionSignals(), cl_px4_mr::CbDisarmPX4::wireCompletionSignals(), cl_px4_mr::CbFollowWaypoints::wireCompletionSignals(), cl_px4_mr::CbGoToLocation::wireCompletionSignals(), cl_px4_mr::CbLand::wireCompletionSignals(), cl_px4_mr::CbReturnToHome::wireCompletionSignals(), cl_px4_mr::CbTakeOff::wireCompletionSignals(), and cl_rgb::CbWaitForFrame::wireCompletionSignals().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ disconnectSmaccSignalObject() [1/2]

template<typename T >
std::enable_if_t< std::is_polymorphic< T >::value > smacc2::ISmaccStateMachine::disconnectSmaccSignalObject ( T * object)
inline

Definition at line 176 of file smacc_state_machine.hpp.

177 {
178 disconnectSmaccSignalObject(dynamic_cast<void *>(object));
179 }
void disconnectSmaccSignalObject(void *object_ptr)

References disconnectSmaccSignalObject().

Here is the call graph for this function:

◆ disconnectSmaccSignalObject() [2/2]

void smacc2::ISmaccStateMachine::disconnectSmaccSignalObject ( void * object_ptr)

Definition at line 83 of file smacc_state_machine.cpp.

84{
85 // DEBUG: this runs for every disposed behavior, reactor, generator and state.
86 RCLCPP_DEBUG(nh_->get_logger(), "[SmaccSignal] Object signal disconnecting %p", object_ptr);
87 if (stateCallbackConnections.count(object_ptr) > 0)
88 {
89 auto callbackSemaphore = stateCallbackConnections[object_ptr];
90 callbackSemaphore->finalize();
91 stateCallbackConnections.erase(object_ptr);
92 }
93 else
94 {
95 RCLCPP_DEBUG(nh_->get_logger(), "[SmaccSignal] No signals found %p", object_ptr);
96 }
97}

References nh_, and stateCallbackConnections.

Referenced by disconnectSmaccSignalObject(), notifyOnStateExited(), and smacc2::ISmaccOrthogonal::onDispose().

Here is the caller graph for this function:

◆ eStop()

void smacc2::ISmaccStateMachine::eStop ( )
virtual

◆ getClientBehavior()

template<typename TOrthogonal , typename TClientBehavior >
TClientBehavior * smacc2::ISmaccStateMachine::getClientBehavior ( int index = 0)
inline

Definition at line 101 of file smacc_state_machine.hpp.

102 {
103 auto orthogonal = this->template getOrthogonal<TOrthogonal>();
104
105 return orthogonal->template getClientBehavior<TClientBehavior>(index);
106 }
TClientBehavior * getClientBehavior(int index=0)

References getClientBehavior(), and getOrthogonal().

Referenced by smacc2::ISmaccState::getClientBehavior(), and getClientBehavior().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ getCurrentState()

ISmaccState * smacc2::ISmaccStateMachine::getCurrentState ( ) const
inline

Definition at line 854 of file smacc_state_machine_impl.hpp.

854{ return this->currentState_.back(); }
std::vector< ISmaccState * > currentState_

References currentState_.

Referenced by smacc2::ISmaccClientBehavior::getTraceStateName(), and cl_nav2z::CpWaypointNavigator::sendNextGoal().

Here is the caller graph for this function:

◆ getCurrentStateCounter()

int64_t smacc2::ISmaccStateMachine::getCurrentStateCounter ( ) const
inline

Definition at line 852 of file smacc_state_machine_impl.hpp.

852{ return this->stateSeqCounter_; }

References stateSeqCounter_.

◆ getCurrentStateInfo()

std::shared_ptr< SmaccStateInfo > smacc2::ISmaccStateMachine::getCurrentStateInfo ( )
inline

Definition at line 148 of file smacc_state_machine.hpp.

148{ return currentStateInfo_; }
std::shared_ptr< SmaccStateInfo > currentStateInfo_

References currentStateInfo_.

◆ getGlobalSMData()

template<typename T >
bool smacc2::ISmaccStateMachine::getGlobalSMData ( const std::string & name,
T & ret )

Definition at line 297 of file smacc_state_machine_impl.hpp.

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}
std::map< std::string, std::pair< std::function< std::string()>, boost::any > > globalData_

References getLogger(), globalData_, and m_mutex_.

Referenced by smacc2::ISmaccOrthogonal::getGlobalSMData(), and smacc2::ISmaccState::getGlobalSMData().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ getLogger()

◆ getMutex()

std::recursive_mutex & smacc2::ISmaccStateMachine::getMutex ( )
inline

Definition at line 212 of file smacc_state_machine.hpp.

212{ return this->m_mutex_; }

References m_mutex_.

◆ getNode()

◆ getOrthogonal()

template<typename TOrthogonal >
TOrthogonal * smacc2::ISmaccStateMachine::getOrthogonal ( )

Definition at line 48 of file smacc_state_machine_impl.hpp.

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}

References smacc2::introspection::demangledTypeName(), getLogger(), m_mutex_, and orthogonals_.

Referenced by getClientBehavior(), and smacc2::ISmaccState::getOrthogonal().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ getOrthogonals()

const std::map< std::string, std::shared_ptr< smacc2::ISmaccOrthogonal > > & smacc2::ISmaccStateMachine::getOrthogonals ( ) const

◆ getStateMachineInfo()

const smacc2::introspection::SmaccStateMachineInfo & smacc2::ISmaccStateMachine::getStateMachineInfo ( )
inline

Definition at line 856 of file smacc_state_machine_impl.hpp.

857{
858 return *this->stateMachineInfo_;
859}

References stateMachineInfo_.

Referenced by smacc2::SmaccState< MostDerived, Context, InnerInitial, historyMode >::getStateInfo().

Here is the caller graph for this function:

◆ getStateMachineName()

std::string smacc2::ISmaccStateMachine::getStateMachineName ( )

Definition at line 282 of file smacc_state_machine.cpp.

283{
284 return demangleSymbol(typeid(*this).name());
285}

References smacc2::introspection::demangleSymbol().

Here is the call graph for this function:

◆ getTransitionLogHistory()

void smacc2::ISmaccStateMachine::getTransitionLogHistory ( const std::shared_ptr< rmw_request_id_t > request_header,
const std::shared_ptr< smacc2_msgs::srv::SmaccGetTransitionHistory::Request > req,
std::shared_ptr< smacc2_msgs::srv::SmaccGetTransitionHistory::Response > res )

Definition at line 242 of file smacc_state_machine.cpp.

246{
247 std::lock_guard<std::mutex> guard(transitionLogMutex_);
248 RCLCPP_WARN(
249 nh_->get_logger(), "Requesting transition log history, current size: %ld",
250 this->transitionLogHistory_.size());
251 res->history.assign(this->transitionLogHistory_.begin(), this->transitionLogHistory_.end());
252}
std::deque< smacc2_msgs::msg::SmaccTransitionLogEntry > transitionLogHistory_

References nh_, transitionLogHistory_, and transitionLogMutex_.

Referenced by initializeROS().

Here is the caller graph for this function:

◆ initializeROS()

void smacc2::ISmaccStateMachine::initializeROS ( const std::string & shortname)
protected

Definition at line 208 of file smacc_state_machine.cpp.

209{
210 RCLCPP_WARN_STREAM(nh_->get_logger(), "State machine base creation: " << shortname);
211 // STATE MACHINE TOPICS
212 stateMachinePub_ = nh_->create_publisher<smacc2_msgs::msg::SmaccStateMachine>(
213 shortname + "/smacc/state_machine_description", rclcpp::QoS(1));
214 stateMachineStatusPub_ = nh_->create_publisher<smacc2_msgs::msg::SmaccStatus>(
215 shortname + "/smacc/status", rclcpp::QoS(1));
216 transitionLogPub_ = nh_->create_publisher<smacc2_msgs::msg::SmaccTransitionLogEntry>(
217 shortname + "/smacc/transition_log", rclcpp::QoS(1));
218 // How many transitions the history service keeps; 0 keeps none. The topic carries every transition.
219 int64_t historySize = nh_->declare_parameter<int64_t>("transition_log_history_size", 1000);
220 if (historySize < 0)
221 {
222 RCLCPP_WARN(nh_->get_logger(), "transition_log_history_size %ld clamped to 0", historySize);
223 historySize = 0;
224 }
225 transitionLogHistorySize_ = static_cast<size_t>(historySize);
226
227 eventsLogPub_ = nh_->create_publisher<smacc2_msgs::msg::SmaccEvent>(
228 shortname + "/smacc/event_log", rclcpp::QoS(100));
229
230 // STATE MACHINE SERVICES
231 transitionHistoryService_ = nh_->create_service<smacc2_msgs::srv::SmaccGetTransitionHistory>(
232 shortname + "/smacc/transition_log_history",
233 std::bind(
234 &ISmaccStateMachine::getTransitionLogHistory, this, std::placeholders::_1,
235 std::placeholders::_2, std::placeholders::_3));
236
237 // Notify signal detector that ROS initialization is complete
238 // This allows the polling loop to start safely accessing ROS objects
240}
rclcpp::Publisher< smacc2_msgs::msg::SmaccStateMachine >::SharedPtr stateMachinePub_
rclcpp::Service< smacc2_msgs::srv::SmaccGetTransitionHistory >::SharedPtr transitionHistoryService_
rclcpp::Publisher< smacc2_msgs::msg::SmaccStatus >::SharedPtr stateMachineStatusPub_
rclcpp::Publisher< smacc2_msgs::msg::SmaccTransitionLogEntry >::SharedPtr transitionLogPub_
rclcpp::Publisher< smacc2_msgs::msg::SmaccEvent >::SharedPtr eventsLogPub_
void getTransitionLogHistory(const std::shared_ptr< rmw_request_id_t > request_header, const std::shared_ptr< smacc2_msgs::srv::SmaccGetTransitionHistory::Request > req, std::shared_ptr< smacc2_msgs::srv::SmaccGetTransitionHistory::Response > res)

References eventsLogPub_, getTransitionLogHistory(), nh_, smacc2::SignalDetector::notifyRosInitialized(), signalDetector_, stateMachinePub_, stateMachineStatusPub_, transitionHistoryService_, transitionLogHistorySize_, and transitionLogPub_.

Referenced by smacc2::SmaccStateMachineBase< DerivedStateMachine, InitialStateType >::initiate_impl().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ joinAsyncClientBehaviorThreads()

void smacc2::ISmaccStateMachine::joinAsyncClientBehaviorThreads ( )

Definition at line 107 of file smacc_state_machine.cpp.

108{
109 // No lock: the scheduler thread has joined, so no transition touches the orthogonals, and
110 // the threads being joined must never take m_mutex_ (Async Thread Locking Rule).
111 for (auto & orthogonalEntry : this->orthogonals_)
112 {
113 for (auto & behaviorsOfOneState : orthogonalEntry.second->getClientBehaviors())
114 {
115 for (auto & clBehavior : behaviorsOfOneState)
116 {
117 auto * asyncBehavior = dynamic_cast<SmaccAsyncClientBehavior *>(clBehavior.get());
118 if (asyncBehavior != nullptr)
119 {
120 asyncBehavior->waitOnEntryThread(true);
121 }
122 }
123 }
124 }
125}

References orthogonals_.

Referenced by smacc2::SignalDetector::joinAsyncClientBehaviorThreads().

Here is the caller graph for this function:

◆ lockStateMachine()

void smacc2::ISmaccStateMachine::lockStateMachine ( const std::string & msg)
private

Definition at line 270 of file smacc_state_machine.cpp.

271{
272 RCLCPP_DEBUG(nh_->get_logger(), "-- locking SM: %s", msg.c_str());
273 m_mutex_.lock();
274}

References m_mutex_, and nh_.

Referenced by notifyOnStateExited().

Here is the caller graph for this function:

◆ notifyOnRuntimeConfigurationFinished()

template<typename StateType >
void smacc2::ISmaccStateMachine::notifyOnRuntimeConfigurationFinished ( StateType * state)

Definition at line 631 of file smacc_state_machine_impl.hpp.

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}
std::atomic< StateMachineInternalAction > stateMachineCurrentAction
void notifyStateConfigured(ISmaccState *currentState)

References currentState_, m_mutex_, smacc2::SignalDetector::notifyStateConfigured(), orthogonals_, signalDetector_, smacc2::STATE_ENTERING, stateMachineCurrentAction, and updateStatusMessage().

Referenced by smacc2::SmaccState< MostDerived, Context, InnerInitial, historyMode >::entryStateInternal().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ notifyOnRuntimeConfigured()

template<typename StateType >
void smacc2::ISmaccStateMachine::notifyOnRuntimeConfigured ( StateType * state)

◆ notifyOnStateEntryEnd()

template<typename StateType >
void smacc2::ISmaccStateMachine::notifyOnStateEntryEnd ( StateType * state)

Definition at line 555 of file smacc_state_machine_impl.hpp.

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}

References currentState_, smacc2::introspection::demangleSymbol(), getLogger(), m_mutex_, smacc2::SignalDetector::notifyStateInitializationFailed(), orthogonals_, signalDetector_, smacc2::STATE_RUNNING, stateMachineCurrentAction, and updateStatusMessage().

Referenced by smacc2::SmaccState< MostDerived, Context, InnerInitial, historyMode >::entryStateInternal().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ notifyOnStateEntryStart()

template<typename StateType >
void smacc2::ISmaccStateMachine::notifyOnStateEntryStart ( StateType * state)

Definition at line 539 of file smacc_state_machine_impl.hpp.

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}

References currentState_, currentStateInfo_, smacc2::introspection::demangleSymbol(), getLogger(), m_mutex_, orthogonals_, stateMachineInfo_, and stateSeqCounter_.

Referenced by smacc2::SmaccState< MostDerived, Context, InnerInitial, historyMode >::entryStateInternal().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ notifyOnStateExited()

template<typename StateType >
void smacc2::ISmaccStateMachine::notifyOnStateExited ( StateType * state)

Definition at line 721 of file smacc_state_machine_impl.hpp.

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}
void unlockStateMachine(const std::string &msg)
void lockStateMachine(const std::string &msg)
void notifyStateExited(ISmaccState *currentState)

References currentState_, smacc2::introspection::demangleSymbol(), disconnectSmaccSignalObject(), getLogger(), lockStateMachine(), smacc2::SignalDetector::notifyStateExited(), orthogonals_, signalDetector_, stateMachineCurrentAction, smacc2::TRANSITIONING, and unlockStateMachine().

Referenced by smacc2::SmaccState< MostDerived, Context, InnerInitial, historyMode >::exit().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ notifyOnStateExiting()

template<typename StateType >
void smacc2::ISmaccStateMachine::notifyOnStateExiting ( StateType * state)

Definition at line 658 of file smacc_state_machine_impl.hpp.

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}

References smacc2::introspection::demangleSymbol(), getLogger(), orthogonals_, smacc2::STATE_EXITING, and stateMachineCurrentAction.

Referenced by smacc2::SmaccState< MostDerived, Context, InnerInitial, historyMode >::exit().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ onInitialize()

void smacc2::ISmaccStateMachine::onInitialize ( )
virtual

this function should be implemented by the user to create the orthogonals

Definition at line 188 of file smacc_state_machine.cpp.

188{}

Referenced by smacc2::SmaccStateMachineBase< DerivedStateMachine, InitialStateType >::initiate_impl().

Here is the caller graph for this function:

◆ onInitialized()

void smacc2::ISmaccStateMachine::onInitialized ( )
protected

Definition at line 201 of file smacc_state_machine.cpp.

202{
203 auto ros_clock = rclcpp::Clock::make_shared();
204 timer_ =
205 rclcpp::create_timer(nh_, ros_clock, 0.5s, [this]() { this->state_machine_visualization(); });
206}
rclcpp::TimerBase::SharedPtr timer_

References nh_, state_machine_visualization(), and timer_.

Referenced by smacc2::SmaccStateMachineBase< DerivedStateMachine, InitialStateType >::initiate_impl().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ onUnhandledStInitializationFailure()

void smacc2::ISmaccStateMachine::onUnhandledStInitializationFailure ( const std::string & stateName,
const std::string & what )
virtual

Definition at line 190 of file smacc_state_machine.cpp.

192{
193 RCLCPP_ERROR(
194 getLogger(),
195 "[SmaccStateMachine] no state reacts to the initialization failure of %s (%s); the state "
196 "machine "
197 "stays in that state with nothing running",
198 stateName.c_str(), what.c_str());
199}

References getLogger().

Referenced by smacc2::SmaccStateMachineBase< DerivedStateMachine, InitialStateType >::unconsumed_event().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ operator=() [1/2]

ISmaccStateMachine & smacc2::ISmaccStateMachine::operator= ( const ISmaccStateMachine & )
delete

◆ operator=() [2/2]

ISmaccStateMachine & smacc2::ISmaccStateMachine::operator= ( ISmaccStateMachine && )
delete

◆ postEvent() [1/3]

template<typename EventType >
void smacc2::ISmaccStateMachine::postEvent ( const boost::intrusive_ptr< EventType > & evHolder,
EventLifeTime evlifetime = EventLifeTime::ABSOLUTE )

Definition at line 210 of file smacc_state_machine_impl.hpp.

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 {
224 auto evinfo = SmaccEventInfo(TypeInfo::getTypeInfoFromType<EventType>());
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}
std::recursive_mutex eventQueueMutex_
void propagateEventToStateReactors(ISmaccState *st, EventType *ev)
static thread_local int reactorWalkDepth_
void queueWorkItem(const SmaccFifoWorker::work_item &item)
static TypeInfo::Ptr getTypeInfoFromType()
std::enable_if< HasEventLabel< T >::value, void >::type EventLabel(std::string &label)
#define eventtypename
smacc2_event

References smacc2::CURRENT_STATE, currentState_, smacc2::introspection::EventLabel(), eventQueueMutex_, eventsLogPub_, eventtypename, getLogger(), smacc2::introspection::TypeInfo::getTypeInfoFromType(), smacc2::SignalDetector::postEvent(), propagateEventToStateReactors(), smacc2::SignalDetector::queueWorkItem(), reactorWalkDepth_, signalDetector_, smacc2_event, smacc2::STATE_EXITING, stateMachineCurrentAction, and smacc2::TRANSITIONING.

Here is the call graph for this function:

◆ postEvent() [2/3]

template<typename EventType >
void smacc2::ISmaccStateMachine::postEvent ( EventLifeTime evlifetime = EventLifeTime::ABSOLUTE)

Definition at line 289 of file smacc_state_machine_impl.hpp.

290{
292 RCLCPP_INFO_STREAM(getLogger(), "Event: " << evname);
293 this->postEvent(makeEvent<EventType>(), evlifetime);
294}
void postEvent(EventType *ev, EventLifeTime evlifetime=EventLifeTime::ABSOLUTE)
boost::intrusive_ptr< EventType > makeEvent(Args &&... args)

References smacc2::introspection::demangleSymbol(), getLogger(), smacc2::makeEvent(), and postEvent().

Here is the call graph for this function:

◆ postEvent() [3/3]

template<typename EventType >
void smacc2::ISmaccStateMachine::postEvent ( EventType * ev,
EventLifeTime evlifetime = EventLifeTime::ABSOLUTE )

Definition at line 203 of file smacc_state_machine_impl.hpp.

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}

References postEvent().

Referenced by smacc2::ISmaccClient::postEvent(), smacc2::ISmaccClient::postEvent(), smacc2::ISmaccClientBehavior::postEvent(), smacc2::ISmaccComponent::postEvent(), smacc2::ISmaccComponent::postEvent(), smacc2::ISmaccState::postEvent(), smacc2::ISmaccState::postEvent(), postEvent(), postEvent(), smacc2::postStInitializationFailure(), and smacc2::StateReactor::setOutputEvent().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ propagateEventToStateReactors()

template<typename EventType >
void smacc2::ISmaccStateMachine::propagateEventToStateReactors ( ISmaccState * st,
EventType * ev )
private

Definition at line 809 of file smacc_state_machine_impl.hpp.

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}
std::string demangleType(const std::type_info *tinfo)

References smacc2::introspection::demangleSymbol(), smacc2::introspection::demangleType(), smacc2::ISmaccState::getClassName(), getLogger(), smacc2::ISmaccState::getParentState(), smacc2::ISmaccState::getStateReactors(), and propagateEventToStateReactors().

Referenced by postEvent(), and propagateEventToStateReactors().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ publishTransition()

void smacc2::ISmaccStateMachine::publishTransition ( const SmaccTransitionInfo & transitionInfo)

Definition at line 170 of file smacc_state_machine.cpp.

171{
172 smacc2_msgs::msg::SmaccTransitionLogEntry transitionLogEntry;
173 transitionLogEntry.timestamp = this->nh_->now();
174 transitionInfoToMsg(transitionInfo, transitionLogEntry.transition);
175 {
176 // Bounded: the vector this used to be grew 1 KB per transition for the life of the process (X).
177 std::lock_guard<std::mutex> guard(transitionLogMutex_);
178 this->transitionLogHistory_.push_back(transitionLogEntry);
180 {
181 this->transitionLogHistory_.pop_front();
182 }
183 }
184
185 transitionLogPub_->publish(transitionLogEntry);
186}
void transitionInfoToMsg(const SmaccTransitionInfo &transition, smacc2_msgs::msg::SmaccTransition &transitionMsg)

References nh_, smacc2::introspection::transitionInfoToMsg(), transitionLogHistory_, transitionLogHistorySize_, transitionLogMutex_, and transitionLogPub_.

Referenced by smacc2::SmaccStateMachineBase< DerivedStateMachine, InitialStateType >::initiate_impl(), and smacc2::ISmaccState::notifyTransitionFromTransitionTypeInfo().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ requiresComponent() [1/2]

template<typename SmaccComponentType >
void smacc2::ISmaccStateMachine::requiresComponent ( const std::string & name,
SmaccComponentType *& storage,
ComponentRequirement requirementType,
ISmaccOrthogonal * first = nullptr )

Definition at line 160 of file smacc_state_machine_impl.hpp.

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}

References smacc2::ISmaccOrthogonal::clients_, smacc2::introspection::demangleSymbol(), getLogger(), smacc2::HARD, m_mutex_, and orthogonals_.

Here is the call graph for this function:

◆ requiresComponent() [2/2]

template<typename SmaccComponentType >
void smacc2::ISmaccStateMachine::requiresComponent ( SmaccComponentType *& storage,
ComponentRequirement requirementType,
ISmaccOrthogonal * first = nullptr )

Definition at line 118 of file smacc_state_machine_impl.hpp.

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}

References smacc2::ISmaccOrthogonal::clients_, smacc2::introspection::demangleSymbol(), getLogger(), smacc2::HARD, m_mutex_, and orthogonals_.

Referenced by smacc2::ISmaccClientBehavior::requiresComponent(), smacc2::ISmaccClientBehavior::requiresComponent(), smacc2::ISmaccOrthogonal::requiresComponent(), smacc2::ISmaccState::requiresComponent(), and smacc2::ISmaccState::requiresComponent().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ reset()

void smacc2::ISmaccStateMachine::reset ( )
virtual

◆ setGlobalSMData()

template<typename T >
void smacc2::ISmaccStateMachine::setGlobalSMData ( const std::string & name,
T value )

Definition at line 332 of file smacc_state_machine_impl.hpp.

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}

References globalData_, m_mutex_, and updateStatusMessage().

Referenced by smacc2::ISmaccOrthogonal::setGlobalSMData(), and smacc2::ISmaccState::setGlobalSMData().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ state_machine_visualization()

void smacc2::ISmaccStateMachine::state_machine_visualization ( )

Definition at line 254 of file smacc_state_machine.cpp.

255{
256 std::lock_guard<std::recursive_mutex> lock(m_mutex_);
257
258 smacc2_msgs::msg::SmaccStateMachine state_machine_msg;
259 state_machine_msg.states = stateMachineInfo_->stateMsgs;
260
261 std::sort(
262 state_machine_msg.states.begin(), state_machine_msg.states.end(),
263 [](const auto & a, const auto & b) { return a.index < b.index; });
264 stateMachinePub_->publish(state_machine_msg);
265
266 status_msg_.header.stamp = this->nh_->now();
268}
smacc2_msgs::msg::SmaccStatus status_msg_

References m_mutex_, nh_, stateMachineInfo_, stateMachinePub_, stateMachineStatusPub_, and status_msg_.

Referenced by onInitialized().

Here is the caller graph for this function:

◆ stop()

void smacc2::ISmaccStateMachine::stop ( )
virtual

Reimplemented in smacc2::SmaccStateMachineBase< DerivedStateMachine, InitialStateType >.

Definition at line 103 of file smacc_state_machine.cpp.

103{}

Referenced by smacc2::SmaccStateMachineBase< DerivedStateMachine, InitialStateType >::stop().

Here is the caller graph for this function:

◆ unlockStateMachine()

void smacc2::ISmaccStateMachine::unlockStateMachine ( const std::string & msg)
private

Definition at line 276 of file smacc_state_machine.cpp.

277{
278 RCLCPP_DEBUG(nh_->get_logger(), "-- unlocking SM: %s", msg.c_str());
279 m_mutex_.unlock();
280}

References m_mutex_, and nh_.

Referenced by notifyOnStateExited().

Here is the caller graph for this function:

◆ updateStatusMessage()

void smacc2::ISmaccStateMachine::updateStatusMessage ( )
private

Definition at line 133 of file smacc_state_machine.cpp.

134{
135 std::lock_guard<std::recursive_mutex> lock(m_mutex_);
136
137 if (currentStateInfo_ != nullptr)
138 {
139 RCLCPP_WARN_STREAM(
140 nh_->get_logger(),
141 "[StateMachine] Setting state active: " << currentStateInfo_->getFullPath());
142
144 {
145 status_msg_.current_states.clear();
146 std::list<const SmaccStateInfo *> ancestorList;
147 currentStateInfo_->getAncestors(ancestorList);
148
149 for (auto & ancestor : ancestorList)
150 {
151 status_msg_.current_states.push_back(ancestor->toShortName());
152 }
153
154 status_msg_.global_variable_names.clear();
155 status_msg_.global_variable_values.clear();
156
157 for (auto entry : this->globalData_)
158 {
159 status_msg_.global_variable_names.push_back(entry.first);
160 status_msg_.global_variable_values.push_back(
161 entry.second.first()); // <- invoke to_string()
162 }
163
164 status_msg_.header.stamp = this->nh_->now();
166 }
167 }
168}

References currentStateInfo_, smacc2::DEBUG, globalData_, m_mutex_, nh_, runMode_, stateMachineStatusPub_, and status_msg_.

Referenced by notifyOnRuntimeConfigurationFinished(), notifyOnStateEntryEnd(), and setGlobalSMData().

Here is the caller graph for this function:

Friends And Related Symbol Documentation

◆ ISmaccState

friend class ISmaccState
friend

Definition at line 292 of file smacc_state_machine.hpp.

◆ SignalDetector

friend class SignalDetector
friend

Definition at line 293 of file smacc_state_machine.hpp.

Member Data Documentation

◆ currentState_

std::vector<ISmaccState *> smacc2::ISmaccStateMachine::currentState_
protected

◆ currentStateInfo_

std::shared_ptr<SmaccStateInfo> smacc2::ISmaccStateMachine::currentStateInfo_
protected

◆ eventQueueMutex_

std::recursive_mutex smacc2::ISmaccStateMachine::eventQueueMutex_
private

Definition at line 252 of file smacc_state_machine.hpp.

Referenced by postEvent().

◆ eventsLogPub_

rclcpp::Publisher<smacc2_msgs::msg::SmaccEvent>::SharedPtr smacc2::ISmaccStateMachine::eventsLogPub_
protected

Definition at line 232 of file smacc_state_machine.hpp.

Referenced by initializeROS(), and postEvent().

◆ globalData_

std::map<std::string, std::pair<std::function<std::string()>, boost::any> > smacc2::ISmaccStateMachine::globalData_
private

Definition at line 264 of file smacc_state_machine.hpp.

Referenced by getGlobalSMData(), setGlobalSMData(), and updateStatusMessage().

◆ m_mutex_

◆ nh_

◆ orthogonals_

◆ reactorWalkDepth_

thread_local int smacc2::ISmaccStateMachine::reactorWalkDepth_ = 0
staticprivate

Definition at line 288 of file smacc_state_machine.hpp.

Referenced by postEvent().

◆ runMode_

smacc2::SMRunMode smacc2::ISmaccStateMachine::runMode_
private

Definition at line 273 of file smacc_state_machine.hpp.

Referenced by ISmaccStateMachine(), and updateStatusMessage().

◆ signalDetector_

SignalDetector* smacc2::ISmaccStateMachine::signalDetector_
private

◆ stateCallbackConnections

std::map<void *, std::shared_ptr<CallbackCounterSemaphore> > smacc2::ISmaccStateMachine::stateCallbackConnections
private

Definition at line 261 of file smacc_state_machine.hpp.

Referenced by createSignalConnection(), and disconnectSmaccSignalObject().

◆ stateMachineCurrentAction

◆ stateMachineInfo_

◆ stateMachinePub_

rclcpp::Publisher<smacc2_msgs::msg::SmaccStateMachine>::SharedPtr smacc2::ISmaccStateMachine::stateMachinePub_
protected

Definition at line 228 of file smacc_state_machine.hpp.

Referenced by initializeROS(), and state_machine_visualization().

◆ stateMachineStatusPub_

rclcpp::Publisher<smacc2_msgs::msg::SmaccStatus>::SharedPtr smacc2::ISmaccStateMachine::stateMachineStatusPub_
protected

◆ stateSeqCounter_

int64_t smacc2::ISmaccStateMachine::stateSeqCounter_ = 0
private

Definition at line 278 of file smacc_state_machine.hpp.

Referenced by getCurrentStateCounter(), and notifyOnStateEntryStart().

◆ status_msg_

smacc2_msgs::msg::SmaccStatus smacc2::ISmaccStateMachine::status_msg_
protected

Definition at line 242 of file smacc_state_machine.hpp.

Referenced by state_machine_visualization(), and updateStatusMessage().

◆ timer_

rclcpp::TimerBase::SharedPtr smacc2::ISmaccStateMachine::timer_
protected

Definition at line 227 of file smacc_state_machine.hpp.

Referenced by onInitialized().

◆ transitionHistoryService_

rclcpp::Service<smacc2_msgs::srv::SmaccGetTransitionHistory>::SharedPtr smacc2::ISmaccStateMachine::transitionHistoryService_
protected

Definition at line 234 of file smacc_state_machine.hpp.

Referenced by initializeROS().

◆ transitionLogHistory_

std::deque<smacc2_msgs::msg::SmaccTransitionLogEntry> smacc2::ISmaccStateMachine::transitionLogHistory_
private

Definition at line 269 of file smacc_state_machine.hpp.

Referenced by getTransitionLogHistory(), and publishTransition().

◆ transitionLogHistorySize_

size_t smacc2::ISmaccStateMachine::transitionLogHistorySize_ = 1000
private

Definition at line 271 of file smacc_state_machine.hpp.

Referenced by initializeROS(), and publishTransition().

◆ transitionLogMutex_

std::mutex smacc2::ISmaccStateMachine::transitionLogMutex_
private

Definition at line 270 of file smacc_state_machine.hpp.

Referenced by getTransitionLogHistory(), and publishTransition().

◆ transitionLogPub_

rclcpp::Publisher<smacc2_msgs::msg::SmaccTransitionLogEntry>::SharedPtr smacc2::ISmaccStateMachine::transitionLogPub_
protected

Definition at line 230 of file smacc_state_machine.hpp.

Referenced by initializeROS(), and publishTransition().


The documentation for this class was generated from the following files: