SMACC2
Loading...
Searching...
No Matches
smacc_signal_detector.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/thread.hpp>
24#include <rclcpp/contexts/default_context.hpp>
25#include <smacc2/common.hpp>
26#include <smacc2_msgs/msg/smacc_status.hpp>
27
28namespace smacc2
29{
35
36// Mostly define the state machine ros thread and receive events state machine components (clients, state elements)
37// This class also contains the event queue of the state machine
39{
40public:
42 SmaccFifoScheduler * scheduler,
44
45 void initialize(ISmaccStateMachine * stateMachine);
46
47 void setProcessorHandle(SmaccFifoScheduler::processor_handle processorHandle);
48
49 // Runs the polling loop into a thread...
50 void runThread();
51
52 // Waits for the polling thread to end...
53 void join();
54
55 void stop();
56
57 void terminateScheduler();
58
59 // Forwards to ISmaccStateMachine::joinAsyncClientBehaviorThreads; no-op before initialize().
61
62 void pollingLoop();
63
64 template <typename EventType>
65 void postEvent(EventType * ev)
66 {
67 boost::intrusive_ptr<EventType> weakPtrEvent = ev;
68 this->scheduler_->queue_event(processorHandle_, weakPtrEvent);
69 }
70
71 // Runs item on the state machine thread, in FIFO order with the queued events.
72 void queueWorkItem(const SmaccFifoWorker::work_item & item)
73 {
74 this->scheduler_->queue_work_item(item);
75 }
76
77 rclcpp::Node::SharedPtr getNode();
78 inline rclcpp::Logger getLogger() { return getNode()->get_logger(); }
79
80 void notifyStateConfigured(ISmaccState * currentState);
81
82 void notifyStateExited(ISmaccState * currentState);
83
84 // The current state's elements are not updated: its initialization failed.
86
87 // Called after state machine ROS initialization is complete (initializeROS)
88 // This signals that orthogonals, clients, and ROS objects are ready
90
91private:
92 void pollOnce();
93
95
96 std::vector<ISmaccUpdatable *> updatableClients_;
97
98 std::vector<std::vector<ISmaccUpdatable *>> updatableStateElements_;
99
101
102 void findUpdatableStateElements(ISmaccState * currentState);
103
104 // Loop rate used when the signal_detector_loop_freq parameter is absent or not positive.
105 static constexpr double kDefaultLoopRateHz = 20.0;
106 // Rate of the start-up wait before the parameter is read: the machine always comes up at this cadence.
107 static constexpr double kInitializationPollRateHz = 20.0;
108
109 // Loop frequency of the signal detector, from the signal_detector_loop_freq parameter.
111
112 std::atomic<bool> end_{false};
113
114 std::atomic<bool> initialized_{false};
115
116 // Flag set after initializeROS() completes - indicates ROS objects are ready
117 std::atomic<bool> rosInitialized_{false};
118
119 rclcpp::Publisher<smacc2_msgs::msg::SmaccStatus>::SharedPtr statusPub_;
120
121 // ---- boost statechart related ----
122
124
125 SmaccFifoScheduler::processor_handle processorHandle_;
126
128
130};
131
132void onSigQuit(int sig);
133
134// Main entry point for any SMACC state machine
135// It instantiates and starts the specified state machine type
136// it uses two threads: a new thread and the current one.
137// The created thread is for the state machine process
138// it locks the current thread to handle events of the state machine
139template <typename StateMachineType>
141{
142 // SIGINT and SIGTERM are left to the handlers rclcpp::init installed. Those only signal a
143 // semaphore; a dedicated rclcpp thread then calls rclcpp::shutdown(), and the on_shutdown
144 // callback registered in SignalDetector::initialize stops the polling loop and
145 // terminates the scheduler. Replacing them here with a handler that called
146 // rclcpp::shutdown() directly ran DDS teardown inside the signal context.
147 ::signal(SIGQUIT, onSigQuit);
148
149 // create the asynchronous state machine scheduler
150 SmaccFifoScheduler scheduler1(true);
151
152 // create the signalDetector component
153 SignalDetector signalDetector(&scheduler1, executionModel);
154
155 // create the asynchronous state machine processor
156 SmaccFifoScheduler::processor_handle sm =
157 scheduler1.create_processor<StateMachineType>(&signalDetector);
158
159 // initialize the asynchronous state machine processor
160 signalDetector.setProcessorHandle(sm);
161
162 scheduler1.initiate_processor(sm);
163
164 //create a thread for the asynchronous state machine processor execution
165 boost::thread schedulerThread(boost::bind(&sc::fifo_scheduler<>::operator(), &scheduler1, 0));
166
167 // use the main thread for the signal detector component (waiting actionclient requests)
168 signalDetector.pollingLoop();
169
170 // After polling loop exits (due to shutdown), terminate the scheduler from main thread
171 // This is safe to call here (not from signal handler) as we're in the main thread context
172 RCLCPP_INFO(rclcpp::get_logger("SMACC"), "Polling loop exited. Terminating scheduler...");
173 signalDetector.terminateScheduler();
174
175 // Wait for scheduler thread to finish
176 RCLCPP_INFO(rclcpp::get_logger("SMACC"), "Waiting for scheduler thread to join...");
177 schedulerThread.join();
178
179 // Wait for the signal thread's Context::shutdown() before destroying anything (study, F-6); not via
180 // rclcpp::shutdown(), which uninstalls the signal handlers so a second SIGINT kills the teardown (Y).
181 if (!rclcpp::ok())
182 {
183 rclcpp::contexts::get_global_default_context()->shutdown("SMACC2 run finished");
184 }
185
186 // No transition is in progress now. Stop and join the onEntry threads of the active state's
187 // async behaviors while the state machine and this signal detector are still alive; the
188 // destructors below would otherwise do it with both half-destroyed.
189 signalDetector.joinAsyncClientBehaviorThreads();
190 RCLCPP_INFO(rclcpp::get_logger("SMACC"), "Scheduler thread terminated. Shutdown complete.");
191}
192
193} // namespace smacc2
SmaccFifoScheduler * scheduler_
static constexpr double kInitializationPollRateHz
void queueWorkItem(const SmaccFifoWorker::work_item &item)
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)
rclcpp::Publisher< smacc2_msgs::msg::SmaccStatus >::SharedPtr statusPub_
void findUpdatableStateElements(ISmaccState *currentState)
ISmaccStateMachine * smaccStateMachine_
void notifyStateConfigured(ISmaccState *currentState)
void onSigQuit(int sig)
void run(ExecutionModel executionModel=ExecutionModel::SINGLE_THREAD_SPINNER)
boost::statechart::fifo_scheduler< SmaccFifoWorker, SmaccAllocator > SmaccFifoScheduler