SMACC2
Loading...
Searching...
No Matches
signal_detector.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 <signal.h>
22#include <chrono>
23#include <memory>
24#include <thread>
25#include <vector>
26
27#include <lttng/tracepoint.h>
28#include <unistd.h>
29#include <rcl_interfaces/msg/parameter_descriptor.hpp>
30
35
36namespace smacc2
37{
38using namespace std::chrono_literals;
39
46: scheduler_(scheduler), executionModel_(executionModel)
47{
48}
49
50rclcpp::Node::SharedPtr SignalDetector::getNode() { return this->smaccStateMachine_->getNode(); }
51
58{
59 smaccStateMachine_ = stateMachine;
61 // A whole number in a config file (20) has to work like 20.0: dynamic typing lets an integer
62 // override through, and the polling loop reads whichever numeric type arrived.
63 rcl_interfaces::msg::ParameterDescriptor loopRateDescriptor;
64 loopRateDescriptor.description = "Polling loop rate of the signal detector, in Hz";
65 loopRateDescriptor.dynamic_typing = true;
66 this->getNode()->declare_parameter(
67 "signal_detector_loop_freq", rclcpp::ParameterValue(kDefaultLoopRateHz), loopRateDescriptor);
68
69 auto context = getNode()->get_node_base_interface()->get_context();
70 context->on_shutdown(
71 [this]()
72 {
73 this->stop();
74 this->terminateScheduler();
75 });
76
77 initialized_ = true;
78}
79
86{
87 this->updatableClients_.clear();
88 for (auto pair : this->smaccStateMachine_->getOrthogonals())
89 {
90 auto & orthogonal = pair.second;
91 auto & clients = orthogonal->getClients();
92
93 for (auto & client : clients)
94 {
95 // updatable client components
96 auto updatableClient = dynamic_cast<ISmaccUpdatable *>(client.get());
97
98 if (updatableClient != nullptr)
99 {
100 RCLCPP_DEBUG_STREAM(
101 getLogger(), "Adding updatable client: " << demangleType(typeid(updatableClient)));
102 this->updatableClients_.push_back(updatableClient);
103 }
104
105 // updatable client components
106 std::vector<std::shared_ptr<ISmaccComponent>> components;
107 client->getComponents(components);
108 for (auto & componententry : components)
109 {
110 auto updatableComponent = dynamic_cast<ISmaccUpdatable *>(componententry.get());
111 if (updatableComponent != nullptr)
112 {
113 RCLCPP_DEBUG_STREAM(
114 getLogger(),
115 "Adding updatable component: " << demangleType(typeid(*updatableComponent)));
116 this->updatableClients_.push_back(updatableComponent);
117 }
118 }
119 }
120 }
121}
122
129{
130 updatableStateElements_.push_back(std::vector<ISmaccUpdatable *>());
131
132 auto & updatableElements = updatableStateElements_.back();
133
134 for (auto pair : this->smaccStateMachine_->getOrthogonals())
135 {
136 auto & orthogonal = pair.second;
137 auto & behaviors = orthogonal->getClientBehaviors().back();
138
139 for (auto & currentBehavior : behaviors)
140 {
141 ISmaccUpdatable * updatableClientBehavior =
142 dynamic_cast<ISmaccUpdatable *>(currentBehavior.get());
143
144 if (updatableClientBehavior != nullptr)
145 {
146 RCLCPP_DEBUG_STREAM(
147 getLogger(),
148 "Adding updatable behavior: " << demangleType(typeid(updatableClientBehavior)));
149 updatableElements.push_back(updatableClientBehavior);
150 }
151 }
152 }
153
154 auto updatableState = dynamic_cast<ISmaccUpdatable *>(currentState);
155 if (updatableState != nullptr)
156 {
157 updatableElements.push_back(updatableState);
158 }
159
160 auto statereactors = currentState->getStateReactors();
161 for (auto & sr : statereactors)
162 {
163 ISmaccUpdatable * updatableStateReactor = dynamic_cast<ISmaccUpdatable *>(sr.get());
164 if (updatableStateReactor != nullptr)
165 {
166 RCLCPP_DEBUG_STREAM(
167 getLogger(),
168 "Adding updatable stateReactorr: " << demangleType(typeid(updatableStateReactor)));
169 updatableElements.push_back(updatableStateReactor);
170 }
171 }
172
173 auto eventgenerators = currentState->getEventGenerators();
174 for (auto & eg : eventgenerators)
175 {
176 ISmaccUpdatable * updatableEventGenerator = dynamic_cast<ISmaccUpdatable *>(eg.get());
177 if (updatableEventGenerator != nullptr)
178 {
179 RCLCPP_DEBUG_STREAM(
180 getLogger(),
181 "Adding updatable eventGenerator: " << demangleType(typeid(updatableEventGenerator)));
182 updatableElements.push_back(updatableEventGenerator);
183 }
184 }
185}
186
193{
194 this->findUpdatableStateElements(currentState);
195}
196
198{
199 this->updatableStateElements_.pop_back();
200}
201
203{
204 if (!this->updatableStateElements_.empty()) this->updatableStateElements_.back().clear();
205}
206
213{
214 RCLCPP_INFO(getLogger(), "[SignalDetector] ROS initialization complete, enabling polling loop");
215 rosInitialized_ = true;
216}
217
223void SignalDetector::setProcessorHandle(SmaccFifoScheduler::processor_handle processorHandle)
224{
225 processorHandle_ = processorHandle;
226}
227
234{
235 signalDetectorThread_ = boost::thread(boost::bind(&SignalDetector::pollingLoop, this));
236}
237
244
250void SignalDetector::stop() { end_ = true; }
251
264
271{
272 if (scheduler_)
273 {
274 RCLCPP_INFO(getLogger(), "[SignalDetector] Terminating scheduler...");
275 scheduler_->terminate();
276 }
277}
278
285{
286 // precondition: smaccStateMachine_ != nullptr
287
288 TRACETOOLS_TRACEPOINT(spinOnce);
289
290 std::lock_guard<std::recursive_mutex> lock(smaccStateMachine_->m_mutex_);
291 try
292 {
294 RCLCPP_DEBUG_STREAM(getLogger(), "Updatable clients: " << this->updatableClients_.size());
295
296 if (this->updatableClients_.size())
297 {
298 auto node = getNode();
299 for (auto * updatableClient : this->updatableClients_)
300 {
301 auto updatableElementNameStr = demangleType(typeid(*updatableClient));
302 auto updatableElementName = updatableElementNameStr.c_str();
303 try
304 {
305 RCLCPP_DEBUG_STREAM(
306 node->get_logger(),
307 "[PollOnce] update client call: " << demangleType(typeid(*updatableClient)));
308
309 TRACETOOLS_TRACEPOINT(smacc2_state_update_start, updatableElementName);
310 updatableClient->executeUpdate(smaccStateMachine_->getNode());
311 TRACETOOLS_TRACEPOINT(smacc2_state_update_end, updatableElementName);
312 }
313 catch (const std::exception & e)
314 {
315 RCLCPP_ERROR_STREAM(
316 node->get_logger(),
317 "Error in updatable elemnent " << updatableElementName << ": " << e.what() << '\n');
318 }
319 }
320 }
321
322 // STATE UPDATABLE ELEMENTS
323 // One load, one decision: the state machine thread can change the phase between two
324 // reads, so the gate must be evaluated on a single snapshot.
325 const StateMachineInternalAction currentAction =
327 if (
333 {
334 RCLCPP_DEBUG_STREAM(
335 getLogger(), "Updatable states: " << this->updatableStateElements_.size());
336
337 for (auto stateElement : this->updatableStateElements_)
338 {
339 for (auto * udpatableStateElement : stateElement)
340 {
341 std::string updatableElementName = demangleType(typeid(*udpatableStateElement));
342 auto updatableElementNameCstr = updatableElementName.c_str();
343
344 RCLCPP_DEBUG_STREAM(
345 getLogger(), "pollOnce update client behavior call: "
346 << demangleType(typeid(*udpatableStateElement)));
347 TRACETOOLS_TRACEPOINT(smacc2_state_update_start, updatableElementNameCstr);
348
349 udpatableStateElement->executeUpdate(smaccStateMachine_->getNode());
350 TRACETOOLS_TRACEPOINT(smacc2_state_update_end, updatableElementNameCstr);
351 }
352 }
353 }
354 }
355 catch (std::exception & ex)
356 {
357 RCLCPP_ERROR(getLogger(), "Exception during Signal Detector update loop. %s.", ex.what());
358 }
359}
360
361// rclcpp::Rate::sleep() goes through rclcpp::Clock::sleep_until, which throws std::runtime_error
362// when the context was shut down between the caller's rclcpp::ok() check and the sleep. Shutdown
363// runs on rclcpp's signal thread, concurrently with the polling loop, so the window is everything
364// an iteration does: pollOnce (including waiting for m_mutex_ during a transition and every
365// update()), the callback drain, and the Rate arithmetic. At shutdown the throw is the expected
366// end of the loop, not an error; anything else is rethrown. Returns false once the context is
367// invalid.
368static bool sleepUnlessShutdown(rclcpp::Rate & rate)
369{
370 try
371 {
372 rate.sleep();
373 }
374 catch (const std::runtime_error &)
375 {
376 if (rclcpp::ok())
377 {
378 throw;
379 }
380 return false;
381 }
382 return true;
383}
384
391{
392 // rclcpp::Node::SharedPtr nh("~"); // use node name as root of the parameter server
393 rclcpp::Node::SharedPtr _;
394 rclcpp::Rate r0(kInitializationPollRateHz);
395
396 // Wait for both SignalDetector::initialize() (called from ISmaccStateMachine constructor)
397 // and ROS initialization to complete (initializeROS called from initiate_impl).
398 // This ensures orthogonals, clients, and ROS objects are fully initialized
399 // before we start polling and accessing them.
400 while ((!initialized_ || !rosInitialized_) && rclcpp::ok() && !end_)
401 {
402 if (!sleepUnlessShutdown(r0))
403 {
404 break;
405 }
406 }
407
408 if (!rclcpp::ok() || end_)
409 {
410 RCLCPP_INFO(getLogger(), "[SignalDetector] Shutdown requested before initialization completed");
411 return;
412 }
413
414 auto nh = getNode();
415
416 // The parameter is declared with the default, so reading it always succeeds; whether the machine's
417 // configuration set it is in the node's parameter overrides (params file, command line).
418 const rclcpp::Parameter loopRateParam = nh->get_parameter("signal_detector_loop_freq");
419 if (loopRateParam.get_type() == rclcpp::ParameterType::PARAMETER_INTEGER)
420 {
421 this->loop_rate_hz = static_cast<double>(loopRateParam.as_int());
422 }
423 else if (loopRateParam.get_type() == rclcpp::ParameterType::PARAMETER_DOUBLE)
424 {
425 this->loop_rate_hz = loopRateParam.as_double();
426 }
427 else
428 {
429 // Any other type is a configuration error: say so and run at the default instead of aborting.
430 RCLCPP_ERROR(
431 getLogger(),
432 "Signal Detector frequency (ros param signal_detector_loop_freq) is of type %s, "
433 "not a number; using the default %lf Hz",
434 loopRateParam.get_type_name().c_str(), kDefaultLoopRateHz);
436 }
437 const auto & overrides = nh->get_node_parameters_interface()->get_parameter_overrides();
438 if (overrides.count("signal_detector_loop_freq") == 0)
439 {
440 RCLCPP_WARN(
441 getLogger(),
442 "Signal Detector frequency (ros param signal_detector_loop_freq) was not set, using default "
443 "frequency: %lf",
444 this->loop_rate_hz);
445 }
446 else
447 {
448 RCLCPP_WARN(
449 getLogger(), "Signal Detector frequency (ros param signal_detector_loop_freq): %lf",
450 this->loop_rate_hz);
451 }
452
453 // A rate of zero or less has no period, and spin_all(0) below spins forever: use the default.
454 if (!(this->loop_rate_hz > 0.0))
455 {
456 RCLCPP_ERROR(
457 getLogger(), "Signal Detector frequency %lf is not positive, using the default %lf Hz",
460 }
461
462 nh->set_parameter(rclcpp::Parameter("signal_detector_loop_freq", this->loop_rate_hz));
463
464 RCLCPP_INFO_STREAM(getLogger(), "[SignalDetector] Loop rate hz:" << loop_rate_hz);
465
467 {
468 RCLCPP_INFO_STREAM(getLogger(), "[SignalDetector] Running in single-threaded mode.");
469
470 // One executor for the whole loop. rclcpp::spin_some(nh) built a new executor on every
471 // iteration, and an executor constructor creates a guard condition, which throws
472 // RCLError if rclcpp::shutdown() lands between the loop condition and that call.
473 // Shutdown now runs on rclcpp's signal thread, concurrently with this loop, so the loop
474 // must tolerate it: an existing executor's spin_all() simply returns once the context
475 // is invalid.
476 rclcpp::executors::SingleThreadedExecutor executor;
477 executor.add_node(nh);
478 rclcpp::Rate r(loop_rate_hz);
479 // Drain every ready callback each iteration, as ROS 1's spinOnce did, bounded by one loop
480 // period. spin_some() took one callback per entity per iteration, sampling faster topics.
481 const auto spinBudget = std::chrono::duration_cast<std::chrono::nanoseconds>(
482 std::chrono::duration<double>(1.0 / loop_rate_hz));
483 const double spinBudgetMs = std::chrono::duration<double, std::milli>(spinBudget).count();
484 while (rclcpp::ok() && !end_)
485 {
486 RCLCPP_INFO_STREAM_THROTTLE(
487 getLogger(), *getNode()->get_clock(), 10000, "[SignalDetector] Heartbeat");
488 pollOnce();
489 // A timer or subscription created on another thread reaches a kept executor only through the
490 // notify guard condition, and that hand-off was missed about once in fifty state entries, leaving
491 // the entity ready and never executed (W). Asking for a rebuild every iteration closes it.
492 nh->get_node_base_interface()->trigger_notify_guard_condition();
493 const auto spinStart = std::chrono::steady_clock::now();
494 executor.spin_all(spinBudget);
495 if (std::chrono::steady_clock::now() - spinStart >= spinBudget)
496 {
497 RCLCPP_WARN_THROTTLE(
498 getLogger(), *getNode()->get_clock(), 5000,
499 "[SignalDetector] callbacks filled the whole loop period (%.1f ms): the loop is "
500 "saturated and runs below %.1f Hz",
501 spinBudgetMs, loop_rate_hz);
502 }
503 if (!sleepUnlessShutdown(r))
504 {
505 break;
506 }
507 }
508 executor.remove_node(nh);
509 }
510 else
511 {
512 RCLCPP_INFO_STREAM(getLogger(), "[SignalDetector] Running in multi-threaded mode.");
513
514 rclcpp::executors::MultiThreadedExecutor executor;
515 // Same hand-off hazard as the single-threaded loop (W); here a timer created before the node is
516 // added, so it is in the executor's first collection, asks for a rebuild once per loop period.
517 auto rebuildTimer = nh->create_wall_timer(
518 std::chrono::duration_cast<std::chrono::nanoseconds>(
519 std::chrono::duration<double>(1.0 / loop_rate_hz)),
520 [nh]() { nh->get_node_base_interface()->trigger_notify_guard_condition(); });
521 executor.add_node(nh);
522 executor.spin();
523 }
524}
525
531// Hard escape hatch. Only async-signal-safe calls: no logging (takes a mutex), no exit()
532// (runs static destructors and atexit handlers in signal context).
533void onSigQuit(int)
534{
535 static const char msg[] = "SMACC: SIGQUIT received, exiting immediately\n";
536 ssize_t unused = ::write(STDERR_FILENO, msg, sizeof(msg) - 1);
537 (void)unused;
538 ::_exit(128 + SIGQUIT);
539}
540
541} // namespace smacc2
rclcpp::Node::SharedPtr getNode()
std::atomic< StateMachineInternalAction > stateMachineCurrentAction
const std::map< std::string, std::shared_ptr< smacc2::ISmaccOrthogonal > > & getOrthogonals() const
std::vector< std::shared_ptr< StateReactor > > & getStateReactors()
std::vector< std::shared_ptr< SmaccEventGenerator > > & getEventGenerators()
SmaccFifoScheduler * scheduler_
static constexpr double kInitializationPollRateHz
void notifyStateExited(ISmaccState *currentState)
void initialize(ISmaccStateMachine *stateMachine)
std::vector< std::vector< ISmaccUpdatable * > > updatableStateElements_
std::atomic< bool > rosInitialized_
static constexpr double kDefaultLoopRateHz
rclcpp::Node::SharedPtr getNode()
SmaccFifoScheduler::processor_handle processorHandle_
SignalDetector(SmaccFifoScheduler *scheduler, ExecutionModel executionModel=ExecutionModel::SINGLE_THREAD_SPINNER)
std::vector< ISmaccUpdatable * > updatableClients_
void setProcessorHandle(SmaccFifoScheduler::processor_handle processorHandle)
void findUpdatableStateElements(ISmaccState *currentState)
ISmaccStateMachine * smaccStateMachine_
void notifyStateConfigured(ISmaccState *currentState)
std::string demangleType(const std::type_info *tinfo)
void onSigQuit(int sig)
static bool sleepUnlessShutdown(rclcpp::Rate &rate)
boost::statechart::fifo_scheduler< SmaccFifoWorker, SmaccAllocator > SmaccFifoScheduler
smacc2_state_update_start
smacc2_state_update_end