SMACC2
signal_detector.cpp
Go to the documentation of this file.
1// Copyright 2021 RobosoftAI 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 <limits>
22#include <memory>
23#include <thread>
24#include <vector>
25
26#include <lttng/tracepoint.h>
30// #include <smacc2/smacc_tracing/trace_provider.hpp>
32
33//#include "tracetools/tracetools.h"
34
35namespace smacc2
36{
37using namespace std::chrono_literals;
44{
45 scheduler_ = scheduler;
46 loop_rate_hz = 20.0;
47 end_ = false;
48 initialized_ = false;
49}
50
51rclcpp::Node::SharedPtr SignalDetector::getNode() { return this->smaccStateMachine_->getNode(); }
52
59{
60 smaccStateMachine_ = stateMachine;
61 lastState_ = std::numeric_limits<unsigned long>::quiet_NaN();
63 this->getNode()->declare_parameter("signal_detector_loop_freq", this->loop_rate_hz);
64
65 initialized_ = true;
66}
67
74{
75 this->updatableClients_.clear();
76 for (auto pair : this->smaccStateMachine_->getOrthogonals())
77 {
78 auto & orthogonal = pair.second;
79 auto & clients = orthogonal->getClients();
80
81 for (auto & client : clients)
82 {
83 // updatable client components
84 auto updatableClient = dynamic_cast<ISmaccUpdatable *>(client.get());
85
86 if (updatableClient != nullptr)
87 {
88 RCLCPP_DEBUG_STREAM(
89 getLogger(), "Adding updatable client: " << demangleType(typeid(updatableClient)));
90 this->updatableClients_.push_back(updatableClient);
91 }
92
93 // updatable client components
94 std::vector<std::shared_ptr<ISmaccComponent>> components;
95 client->getComponents(components);
96 for (auto & componententry : components)
97 {
98 auto updatableComponent = dynamic_cast<ISmaccUpdatable *>(componententry.get());
99 if (updatableComponent != nullptr)
100 {
101 RCLCPP_DEBUG_STREAM(
102 getLogger(),
103 "Adding updatable component: " << demangleType(typeid(*updatableComponent)));
104 this->updatableClients_.push_back(updatableComponent);
105 }
106 }
107 }
108 }
109}
110
117{
118 this->updatableStateElements_.clear();
119 for (auto pair : this->smaccStateMachine_->getOrthogonals())
120 {
121 auto & orthogonal = pair.second;
122 auto & behaviors = orthogonal->getClientBehaviors();
123
124 for (auto & currentBehavior : behaviors)
125 {
126 ISmaccUpdatable * updatableClientBehavior =
127 dynamic_cast<ISmaccUpdatable *>(currentBehavior.get());
128
129 if (updatableClientBehavior != nullptr)
130 {
131 RCLCPP_DEBUG_STREAM(
132 getLogger(),
133 "Adding updatable behavior: " << demangleType(typeid(updatableClientBehavior)));
134 this->updatableStateElements_.push_back(updatableClientBehavior);
135 }
136 }
137 }
138
139 auto updatableState = dynamic_cast<ISmaccUpdatable *>(currentState);
140 if (updatableState != nullptr)
141 {
142 this->updatableStateElements_.push_back(updatableState);
143 }
144
145 auto statereactors = currentState->getStateReactors();
146 for (auto & sr : statereactors)
147 {
148 ISmaccUpdatable * updatableStateReactor = dynamic_cast<ISmaccUpdatable *>(sr.get());
149 if (updatableStateReactor != nullptr)
150 {
151 RCLCPP_DEBUG_STREAM(
152 getLogger(),
153 "Adding updatable stateReactorr: " << demangleType(typeid(updatableStateReactor)));
154 this->updatableStateElements_.push_back(updatableStateReactor);
155 }
156 }
157
158 auto eventgenerators = currentState->getEventGenerators();
159 for (auto & eg : eventgenerators)
160 {
161 ISmaccUpdatable * updatableEventGenerator = dynamic_cast<ISmaccUpdatable *>(eg.get());
162 if (updatableEventGenerator != nullptr)
163 {
164 RCLCPP_DEBUG_STREAM(
165 getLogger(),
166 "Adding updatable eventGenerator: " << demangleType(typeid(updatableEventGenerator)));
167 this->updatableStateElements_.push_back(updatableEventGenerator);
168 }
169 }
170}
171
177void SignalDetector::setProcessorHandle(SmaccFifoScheduler::processor_handle processorHandle)
178{
179 processorHandle_ = processorHandle;
180}
181
188{
189 signalDetectorThread_ = boost::thread(boost::bind(&SignalDetector::pollingLoop, this));
190}
191
198
204void SignalDetector::stop() { end_ = true; }
205
212{
213 // precondition: smaccStateMachine_ != nullptr
214
215 //TRACEPOINT( spinOnce);
216 TRACEPOINT(spinOnce);
217
218 std::lock_guard<std::recursive_mutex> lock(smaccStateMachine_->m_mutex_);
219 try
220 {
221 //smaccStateMachine_->lockStateMachine("update behaviors");
222
223 long currentStateIndex = smaccStateMachine_->getCurrentStateCounter();
224 auto currentState = smaccStateMachine_->getCurrentState();
225
226 if (currentState != nullptr)
227 {
228 RCLCPP_INFO_THROTTLE(
229 getLogger(), *(getNode()->get_clock()), 10000,
230 "[SignalDetector] heartbeat. Current State: %s",
231 demangleType(typeid(*currentState)).c_str());
232 }
233
235 RCLCPP_DEBUG_STREAM(getLogger(), "updatable clients: " << this->updatableClients_.size());
236
237 if (this->updatableClients_.size())
238 {
239 auto node = getNode();
240 for (auto * updatableClient : this->updatableClients_)
241 {
242 auto updatableElementName = demangleType(typeid(*updatableClient)).c_str();
243 try
244 {
245 RCLCPP_DEBUG_STREAM(
246 node->get_logger(),
247 "[PollOnce] update client call: " << demangleType(typeid(*updatableClient)));
248
249 TRACEPOINT(smacc2_state_update_start, updatableElementName);
250 updatableClient->executeUpdate(smaccStateMachine_->getNode());
251 TRACEPOINT(smacc2_state_update_start, updatableElementName);
252 }
253 catch (const std::exception & e)
254 {
255 RCLCPP_ERROR_STREAM(
256 node->get_logger(),
257 "Error in updatable elemnent " << updatableElementName << ": " << e.what() << '\n');
258 }
259 }
260 }
261
262 // STATE UPDATABLE ELEMENTS
263 if (
266 this->smaccStateMachine_->stateMachineCurrentAction !=
268 this->smaccStateMachine_->stateMachineCurrentAction !=
270 {
271 // we do not update updatable elements during trasitioning or configuration of states
272 RCLCPP_DEBUG_STREAM(getLogger(), "[SignalDetector] update behaviors. checking current state");
273
274 if (currentState != nullptr)
275 {
276 RCLCPP_DEBUG_STREAM(getLogger(), "[SignalDetector] current state: " << currentStateIndex);
277 RCLCPP_DEBUG_STREAM(
278 getLogger(), "[SignalDetector] last state: " << this->lastState_.load());
279
280 if (currentStateIndex != 0)
281 {
282 if (currentStateIndex != (long)this->lastState_.load())
283 {
284 RCLCPP_DEBUG_STREAM(
285 getLogger(),
286 "[PollOnce] detected new state, refreshing updatable client "
287 "behavior table");
288 // we are in a new state, refresh the updatable client behaviors table
289 this->lastState_.store(currentStateIndex);
290 this->findUpdatableStateElements(currentState);
291 }
292
293 RCLCPP_DEBUG_STREAM(
294 getLogger(),
295 "[SignalDetector] updatable state elements: " << this->updatableStateElements_.size());
296 auto node = getNode();
297 for (auto * udpatableStateElement : this->updatableStateElements_)
298 {
299 auto updatableElementName = demangleType(typeid(*udpatableStateElement)).c_str();
300 try
301 {
302 RCLCPP_DEBUG_STREAM(
303 getLogger(),
304 "[SignalDetector] update client behavior call: " << updatableElementName);
305
306 TRACEPOINT(smacc2_state_update_start, updatableElementName);
307 udpatableStateElement->executeUpdate(smaccStateMachine_->getNode());
308 TRACEPOINT(smacc2_state_update_start, updatableElementName);
309 }
310 catch (const std::exception & e)
311 {
312 RCLCPP_ERROR_STREAM(
313 node->get_logger(),
314 "Error in updatable elemnent " << updatableElementName << ": " << e.what() << '\n');
315 }
316 }
317 }
318 }
319 }
320 }
321 catch (std::exception & ex)
322 {
323 RCLCPP_ERROR(getLogger(), "Exception during Signal Detector update loop. %s", ex.what());
324 }
325
326 auto nh = this->getNode();
327 rclcpp::spin_some(nh);
328 //smaccStateMachine_->unlockStateMachine("update behaviors");
329}
330
337{
338 // rclcpp::Node::SharedPtr nh("~"); // use node name as root of the parameter server
339 rclcpp::Node::SharedPtr _;
340 rclcpp::Rate r0(20);
341
342 while (!initialized_)
343 {
344 r0.sleep();
345 }
346
347 auto nh = getNode();
348
349 if (!nh->get_parameter("signal_detector_loop_freq", this->loop_rate_hz))
350 {
351 RCLCPP_WARN(
352 getLogger(),
353 "Signal detector frequency (ros param signal_detector_loop_freq) was not set, using default "
354 "frequency: "
355 "%lf",
356 this->loop_rate_hz);
357 }
358 else
359 {
360 RCLCPP_WARN(
361 getLogger(), "Signal detector frequency (ros param signal_detector_loop_freq): %lf",
362 this->loop_rate_hz);
363 }
364
365 nh->set_parameter(rclcpp::Parameter("signal_detector_loop_freq", this->loop_rate_hz));
366
367 RCLCPP_INFO_STREAM(getLogger(), "[SignalDetector] loop rate hz:" << loop_rate_hz);
368
369 rclcpp::Rate r(loop_rate_hz);
370
371 while (rclcpp::ok() && !end_)
372 {
373 pollOnce();
374 rclcpp::spin_some(nh);
375 r.sleep();
376 }
377}
378} // namespace smacc2
StateMachineInternalAction stateMachineCurrentAction
rclcpp::Node::SharedPtr getNode()
const std::map< std::string, std::shared_ptr< smacc2::ISmaccOrthogonal > > & getOrthogonals() const
unsigned long getCurrentStateCounter() const
std::vector< std::shared_ptr< StateReactor > > & getStateReactors()
Definition: smacc_state.hpp:80
std::vector< std::shared_ptr< SmaccEventGenerator > > & getEventGenerators()
Definition: smacc_state.hpp:82
SmaccFifoScheduler * scheduler_
void initialize(ISmaccStateMachine *stateMachine)
SignalDetector(SmaccFifoScheduler *scheduler)
std::atomic< unsigned long > lastState_
std::vector< ISmaccUpdatable * > updatableStateElements_
rclcpp::Node::SharedPtr getNode()
SmaccFifoScheduler::processor_handle processorHandle_
std::vector< ISmaccUpdatable * > updatableClients_
void setProcessorHandle(SmaccFifoScheduler::processor_handle processorHandle)
void findUpdatableStateElements(ISmaccState *currentState)
ISmaccStateMachine * smaccStateMachine_
std::atomic< bool > initialized_
std::string demangleType(const std::type_info *tinfo)
boost::statechart::fifo_scheduler< SmaccFifoWorker, SmaccAllocator > SmaccFifoScheduler
void TRACEPOINT(spinOnce)
smacc2_state_update_start