SMACC2
Loading...
Searching...
No Matches
smacc_state_machine.cpp
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#include <rcl/time.h>
22#include <chrono>
23#include <functional>
29#include <smacc2_msgs/msg/smacc_status.hpp>
30#include <smacc2_msgs/msg/smacc_transition_log_entry.hpp>
31
32namespace smacc2
33{
34thread_local int ISmaccStateMachine::reactorWalkDepth_ = 0;
35
36using namespace std::chrono_literals;
37using namespace smacc2::introspection;
39 std::string stateMachineName, SignalDetector * signalDetector,
40 const rclcpp::NodeOptions & nodeOptions)
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}
70
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}
82
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}
98
99rclcpp::Node::SharedPtr ISmaccStateMachine::getNode() { return this->nh_; }
100
102
104
106
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}
126
127const std::map<std::string, std::shared_ptr<smacc2::ISmaccOrthogonal>> &
129{
130 return this->orthogonals_;
131}
132
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}
169
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}
187
189
191 const std::string & stateName, const std::string & what)
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}
200
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}
207
208void ISmaccStateMachine::initializeROS(const std::string & shortname)
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}
241
243 const std::shared_ptr<rmw_request_id_t> /*request_header*/,
244 const std::shared_ptr<smacc2_msgs::srv::SmaccGetTransitionHistory::Request> /*req*/,
245 std::shared_ptr<smacc2_msgs::srv::SmaccGetTransitionHistory::Response> res)
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}
253
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}
269
270void ISmaccStateMachine::lockStateMachine(const std::string & msg)
271{
272 RCLCPP_DEBUG(nh_->get_logger(), "-- locking SM: %s", msg.c_str());
273 m_mutex_.lock();
274}
275
276void ISmaccStateMachine::unlockStateMachine(const std::string & msg)
277{
278 RCLCPP_DEBUG(nh_->get_logger(), "-- unlocking SM: %s", msg.c_str());
279 m_mutex_.unlock();
280}
281
283{
284 return demangleSymbol(typeid(*this).name());
285}
286
288
289} // namespace smacc2
std::map< std::string, std::shared_ptr< smacc2::ISmaccOrthogonal > > orthogonals_
void publishTransition(const SmaccTransitionInfo &transitionInfo)
rclcpp::Publisher< smacc2_msgs::msg::SmaccStateMachine >::SharedPtr stateMachinePub_
std::shared_ptr< SmaccStateInfo > currentStateInfo_
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
void disconnectSmaccSignalObject(void *object_ptr)
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())
static thread_local int reactorWalkDepth_
void initializeROS(const std::string &shortname)
void unlockStateMachine(const std::string &msg)
rclcpp::TimerBase::SharedPtr timer_
rclcpp::Publisher< smacc2_msgs::msg::SmaccTransitionLogEntry >::SharedPtr transitionLogPub_
std::map< void *, std::shared_ptr< CallbackCounterSemaphore > > stateCallbackConnections
void lockStateMachine(const std::string &msg)
smacc2_msgs::msg::SmaccStatus status_msg_
std::shared_ptr< SmaccStateMachineInfo > stateMachineInfo_
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)
void initialize(ISmaccStateMachine *stateMachine)
rclcpp::Node::SharedPtr globalNh_
std::string demangleSymbol()
void transitionInfoToMsg(const SmaccTransitionInfo &transition, smacc2_msgs::msg::SmaccTransition &transitionMsg)