SMACC2
Loading...
Searching...
No Matches
smacc_state_machine.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#pragma once
21
22#include <atomic>
23#include <boost/any.hpp>
24#include <deque>
25#include <map>
26#include <mutex>
27#include <type_traits>
28
29#include <smacc2/common.hpp>
34
35#include <smacc2_msgs/msg/smacc_state_machine.hpp>
36#include <smacc2_msgs/msg/smacc_status.hpp>
37#include <smacc2_msgs/msg/smacc_transition_log_entry.hpp>
38#include <smacc2_msgs/srv/smacc_get_transition_history.hpp>
39
43
44namespace smacc2
45{
46using namespace smacc2::introspection;
47
48enum class EventLifeTime
49{
51 CURRENT_STATE /*events are discarded if we are leaving the state it were created. I is used for client behaviors whose lifetime is associated to state*/
52};
53
55{
61 STATE_MACHINE_INITIALIZING // before the initial state is constructed
62};
63
64// This class describes the concept of Smacc State Machine in an abastract way.
65// The SmaccStateMachineBase inherits from this state machine and from
66// statechart::StateMachine<> (via multiple inheritance)
68{
69public:
71 std::string stateMachineName, SignalDetector * signalDetector,
72 const rclcpp::NodeOptions & nodeOptions = rclcpp::NodeOptions());
73
74 virtual ~ISmaccStateMachine();
75
76 // Not copyable or movable. This turns an accidental copy, such as a missing & in
77 // "auto & sm = *stateMachine;", into a compile error instead of calls on a detached copy.
82
83 virtual void reset();
84
85 virtual void stop();
86
87 virtual void eStop();
88
89 // Asks every async client behavior of the active state(s) to finish and joins its onEntry
90 // thread. Called from run<> after the scheduler thread has joined and before this object
91 // is destroyed; ~state_machine destroys the active states without exit actions, so nothing
92 // else stops those threads at shutdown. Runs no onExit code.
94
95 template <typename TOrthogonal>
96 TOrthogonal * getOrthogonal();
97
98 // gets the client behavior in a given orthogonal
99 // the index is used to distinguish between multiple client behaviors of the same type
100 template <typename TOrthogonal, typename TClientBehavior>
101 inline TClientBehavior * getClientBehavior(int index = 0)
102 {
103 auto orthogonal = this->template getOrthogonal<TOrthogonal>();
104
105 return orthogonal->template getClientBehavior<TClientBehavior>(index);
106 }
107
108 const std::map<std::string, std::shared_ptr<smacc2::ISmaccOrthogonal>> & getOrthogonals() const;
109
110 // The clients of `first`, when given, are searched before those of the other orthogonals:
111 // a behavior passes its own orthogonal, so that with two clients of one type it gets its own.
112 template <typename SmaccComponentType>
114 SmaccComponentType *& storage, ComponentRequirement requirementType,
115 ISmaccOrthogonal * first = nullptr);
116
117 template <typename SmaccComponentType>
119 const std::string & name, SmaccComponentType *& storage, ComponentRequirement requirementType,
120 ISmaccOrthogonal * first = nullptr);
121
122 // Takes ownership of `ev` (must be allocated with `new`); the caller must not use it after
123 // this call. Released by the scheduler after dispatch, or here if discarded or on exception.
124 template <typename EventType>
125 void postEvent(EventType * ev, EventLifeTime evlifetime = EventLifeTime::ABSOLUTE);
126
127 // The same for an event created with makeEvent(); the caller may keep its pointer.
128 template <typename EventType>
129 void postEvent(
130 const boost::intrusive_ptr<EventType> & evHolder,
132
133 template <typename EventType>
135
136 // gets data from the state machine blackboard
137 template <typename T>
138 bool getGlobalSMData(const std::string & name, T & ret);
139
140 // sets data in the state machine blackboard
141 template <typename T>
142 void setGlobalSMData(const std::string & name, T value);
143
144 std::string getStateMachineName();
145
147
148 inline std::shared_ptr<SmaccStateInfo> getCurrentStateInfo() { return currentStateInfo_; }
149
150 void publishTransition(const SmaccTransitionInfo & transitionInfo);
151
153 virtual void onInitialize();
154
155 // Called when a state's runtimeConfigure or onEntry threw and no state, up to the outermost
156 // container, reacted to EvStInitializationFailure. The default logs; the machine stays in that state.
158 const std::string & stateName, const std::string & what);
159
161 const std::shared_ptr<rmw_request_id_t> request_header,
162 const std::shared_ptr<smacc2_msgs::srv::SmaccGetTransitionHistory::Request> req,
163 std::shared_ptr<smacc2_msgs::srv::SmaccGetTransitionHistory::Response> res);
164
165 template <typename TSmaccSignal, typename TMemberFunctionPrototype, typename TSmaccObjectType>
167 TSmaccSignal & signal, TMemberFunctionPrototype callback, TSmaccObjectType * object);
168
169 // Finalizes and erases the signal connections registered by a state-scoped object.
170 // The typed overload normalizes the key with dynamic_cast<void *> (the complete object's
171 // address), as createSignalConnection does, so a base-subobject pointer and the
172 // most-derived pointer of the same object always map to the same entry.
173 void disconnectSmaccSignalObject(void * object_ptr);
174
175 template <typename T>
176 std::enable_if_t<std::is_polymorphic<T>::value> disconnectSmaccSignalObject(T * object)
177 {
178 disconnectSmaccSignalObject(dynamic_cast<void *>(object));
179 }
180
181 template <typename StateType>
182 void notifyOnStateEntryStart(StateType * state);
183
184 template <typename StateType>
185 void notifyOnStateEntryEnd(StateType * state);
186
187 template <typename StateType>
188 void notifyOnRuntimeConfigured(StateType * state);
189
190 template <typename StateType>
191 void notifyOnStateExiting(StateType * state);
192
193 template <typename StateType>
194 void notifyOnStateExited(StateType * state);
195
196 template <typename StateType>
197 void notifyOnRuntimeConfigurationFinished(StateType * state);
198
199 inline int64_t getCurrentStateCounter() const;
200
201 inline ISmaccState * getCurrentState() const;
202
204
205 template <typename InitialStateType>
207
208 rclcpp::Node::SharedPtr getNode();
209
210 inline rclcpp::Logger getLogger() { return nh_->get_logger(); }
211
212 inline std::recursive_mutex & getMutex() { return this->m_mutex_; }
213
214protected:
216
217 void initializeROS(const std::string & shortname);
218
219 void onInitialized();
220
221 template <typename TOrthogonal>
222 void createOrthogonal();
223
224 // The node handle for this state
225 rclcpp::Node::SharedPtr nh_;
226
227 rclcpp::TimerBase::SharedPtr timer_;
228 rclcpp::Publisher<smacc2_msgs::msg::SmaccStateMachine>::SharedPtr stateMachinePub_;
229 rclcpp::Publisher<smacc2_msgs::msg::SmaccStatus>::SharedPtr stateMachineStatusPub_;
230 rclcpp::Publisher<smacc2_msgs::msg::SmaccTransitionLogEntry>::SharedPtr transitionLogPub_;
231
232 rclcpp::Publisher<smacc2_msgs::msg::SmaccEvent>::SharedPtr eventsLogPub_;
233
234 rclcpp::Service<smacc2_msgs::srv::SmaccGetTransitionHistory>::SharedPtr transitionHistoryService_;
235
236 // if it is null, you may be located in a transition. There is a small gap of time where internally
237 // this currentState_ is null. This may change in the future.
238 std::vector<ISmaccState *> currentState_;
239
240 std::shared_ptr<SmaccStateInfo> currentStateInfo_;
241
242 smacc2_msgs::msg::SmaccStatus status_msg_;
243
244 // orthogonals
245 std::map<std::string, std::shared_ptr<smacc2::ISmaccOrthogonal>> orthogonals_;
246
247protected:
248 std::shared_ptr<SmaccStateMachineInfo> stateMachineInfo_;
249
250private:
251 std::recursive_mutex m_mutex_;
252 std::recursive_mutex eventQueueMutex_;
253
254 // Written on the state machine thread (notifyOnState* / notifyOnRuntimeConfigured), read
255 // by SignalDetector::pollOnce on the polling thread and by postEvent on any thread.
256 // Atomic so every reader sees the latest phase; initialized so pollOnce has a defined
257 // value before the first state exists.
260
261 std::map<void *, std::shared_ptr<CallbackCounterSemaphore>> stateCallbackConnections;
262
263 // shared variables
264 std::map<std::string, std::pair<std::function<std::string()>, boost::any>> globalData_;
265
266 // contains the whole history of transitions of the state machine
267 // The last transition_log_history_size transitions, for the history service. Pushed on the state
268 // machine thread, copied on the executor thread; its own leaf mutex, never m_mutex_ (X).
269 std::deque<smacc2_msgs::msg::SmaccTransitionLogEntry> transitionLogHistory_;
272
274
275 // Event to notify to the signaldetection thread that a request has been created...
277
278 int64_t stateSeqCounter_ = 0;
279
280 void lockStateMachine(const std::string & msg);
281
282 void unlockStateMachine(const std::string & msg);
283
284 template <typename EventType>
285 void propagateEventToStateReactors(ISmaccState * st, EventType * ev);
286
287 // Depth of the reactor walk on the calling thread; nonzero only inside the walk work item.
288 static thread_local int reactorWalkDepth_;
289
290 void updateStatusMessage();
291
292 friend class ISmaccState;
293 friend class SignalDetector;
294};
295} // namespace smacc2
296
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_
void publishTransition(const SmaccTransitionInfo &transitionInfo)
rclcpp::Publisher< smacc2_msgs::msg::SmaccStateMachine >::SharedPtr stateMachinePub_
std::shared_ptr< SmaccStateInfo > currentStateInfo_
TClientBehavior * getClientBehavior(int index=0)
rclcpp::Node::SharedPtr getNode()
std::map< std::string, std::pair< std::function< std::string()>, boost::any > > globalData_
std::deque< smacc2_msgs::msg::SmaccTransitionLogEntry > transitionLogHistory_
virtual void onUnhandledStInitializationFailure(const std::string &stateName, const std::string &what)
rclcpp::Service< smacc2_msgs::srv::SmaccGetTransitionHistory >::SharedPtr transitionHistoryService_
virtual void onInitialize()
this function should be implemented by the user to create the orthogonals
ISmaccStateMachine(const ISmaccStateMachine &)=delete
ISmaccStateMachine(ISmaccStateMachine &&)=delete
std::atomic< StateMachineInternalAction > stateMachineCurrentAction
void notifyOnRuntimeConfigurationFinished(StateType *state)
void disconnectSmaccSignalObject(void *object_ptr)
smacc2::SmaccSignalConnection createSignalConnection(TSmaccSignal &signal, TMemberFunctionPrototype callback, TSmaccObjectType *object)
const std::map< std::string, std::shared_ptr< smacc2::ISmaccOrthogonal > > & getOrthogonals() const
rclcpp::Publisher< smacc2_msgs::msg::SmaccStatus >::SharedPtr stateMachineStatusPub_
ISmaccStateMachine(std::string stateMachineName, SignalDetector *signalDetector, const rclcpp::NodeOptions &nodeOptions=rclcpp::NodeOptions())
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_
std::shared_ptr< SmaccStateInfo > getCurrentStateInfo()
void initializeROS(const std::string &shortname)
ISmaccStateMachine & operator=(const ISmaccStateMachine &)=delete
void unlockStateMachine(const std::string &msg)
rclcpp::TimerBase::SharedPtr timer_
rclcpp::Publisher< smacc2_msgs::msg::SmaccTransitionLogEntry >::SharedPtr transitionLogPub_
void notifyOnStateExiting(StateType *state)
std::map< void *, std::shared_ptr< CallbackCounterSemaphore > > stateCallbackConnections
void lockStateMachine(const std::string &msg)
void notifyOnRuntimeConfigured(StateType *state)
ISmaccStateMachine & operator=(ISmaccStateMachine &&)=delete
smacc2_msgs::msg::SmaccStatus status_msg_
void requiresComponent(SmaccComponentType *&storage, ComponentRequirement requirementType, ISmaccOrthogonal *first=nullptr)
std::enable_if_t< std::is_polymorphic< T >::value > disconnectSmaccSignalObject(T *object)
std::shared_ptr< SmaccStateMachineInfo > stateMachineInfo_
void postEvent(EventType *ev, EventLifeTime evlifetime=EventLifeTime::ABSOLUTE)
rclcpp::Publisher< smacc2_msgs::msg::SmaccEvent >::SharedPtr eventsLogPub_
std::recursive_mutex & getMutex()
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)
void notifyOnStateEntryStart(StateType *state)
boost::signals2::connection SmaccSignalConnection
SMRunMode
Definition common.hpp:76
ComponentRequirement
Definition common.hpp:82