SMACC2
Loading...
Searching...
No Matches
cp_action_client.hpp
Go to the documentation of this file.
1// Copyright 2024 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#pragma once
16
17#include <smacc2/component.hpp>
21
22#include <chrono>
23#include <functional>
24#include <future>
25#include <mutex>
26#include <optional>
27#include <rclcpp_action/rclcpp_action.hpp>
28
29namespace smacc2
30{
31namespace client_core_components
32{
33using namespace smacc2::default_events;
34
35template <typename ActionType>
37{
38public:
39 // Type aliases
40 using ActionClient = rclcpp_action::Client<ActionType>;
41 using Goal = typename ActionType::Goal;
42 using Feedback = typename ActionType::Feedback;
43 using Result = typename ActionType::Result;
44 using GoalHandle = rclcpp_action::ClientGoalHandle<ActionType>;
45 using WrappedResult = typename GoalHandle::WrappedResult;
46 using SendGoalOptions = typename ActionClient::SendGoalOptions;
48 std::function<void(std::shared_future<typename GoalHandle::SharedPtr>)>;
49 using FeedbackCallback = typename GoalHandle::FeedbackCallback;
50 using ResultCallback = typename GoalHandle::ResultCallback;
51
52 // Configuration options
53 std::optional<std::string> actionServerName;
54 std::optional<std::chrono::milliseconds> serverTimeout;
55
56 // SMACC2 Signals for component communication
63
64 // Event posting functions (set during orthogonal allocation)
65 std::function<void(const WrappedResult &)> postSuccessEvent;
66 std::function<void(const WrappedResult &)> postAbortedEvent;
67 std::function<void(const WrappedResult &)> postCancelledEvent;
68 std::function<void(const Feedback &)> postFeedbackEvent;
69
70 // Constructor
71 CpActionClient() = default;
72
74
75 ~CpActionClient() override = default;
76
77 // Public API
78 std::shared_future<typename GoalHandle::SharedPtr> sendGoal(
79 Goal & goal, typename smacc2::SmaccSignal<void(const WrappedResult &)>::WeakPtr resultCallback =
80 typename smacc2::SmaccSignal<void(const WrappedResult &)>::WeakPtr())
81 {
82 // actionMutex_ is never held across a rclcpp_action call: those take rclcpp_action's own
83 // mutexes, and holding ours across them was the first edge of the lock cycle (study, F-1).
84 std::shared_ptr<ActionClient> client;
85 FeedbackCallback feedbackCallback;
86 {
87 std::lock_guard<std::mutex> lock(actionMutex_);
88 client = client_;
89 feedbackCallback = feedbackCallback_;
90 }
91
92 if (client == nullptr)
93 {
94 RCLCPP_ERROR_STREAM(
95 getLogger(), "[" << this->getName()
96 << "] Cannot send goal: action client not initialized (was the "
97 "component created with an action server name?)");
98 return std::shared_future<typename GoalHandle::SharedPtr>();
99 }
100
101 SendGoalOptions options;
102
103 // Set up feedback callback
104 options.feedback_callback = feedbackCallback;
105
106 // Goal acceptance/rejection notification. Without this a rejected goal is
107 // silent: the result callback never fires and no signal is emitted.
108 options.goal_response_callback = [this](typename GoalHandle::SharedPtr goalHandle)
109 {
110 if (goalHandle != nullptr)
111 {
112 RCLCPP_INFO_STREAM(getLogger(), "[" << this->getName() << "] Goal accepted by server");
114 }
115 else
116 {
117 RCLCPP_ERROR_STREAM(getLogger(), "[" << this->getName() << "] Goal rejected by server");
119 }
120 };
121
122 // Set up result callback
123 // No actionMutex_ here: it guards nothing this lambda touches, and rclcpp_action runs it under
124 // the goal handle's mutex, which would close a lock cycle with sendGoal (study, F-1).
125 options.result_callback = [this, resultCallback](const WrappedResult & result)
126 {
127 RCLCPP_INFO_STREAM(
128 getLogger(), "[" << this->getName() << "] Action result callback, goal id: "
129 << rclcpp_action::to_string(result.goal_id));
130
131 auto resultCallbackPtr = resultCallback.lock();
132 if (resultCallbackPtr != nullptr)
133 {
134 RCLCPP_INFO_STREAM(getLogger(), "[" << this->getName() << "] Calling user result callback");
135 (*resultCallbackPtr)(result);
136 }
137 else
138 {
139 RCLCPP_INFO_STREAM(
140 getLogger(), "[" << this->getName() << "] Using default result handling");
141 this->onResult(result);
142 }
143 };
144
145 RCLCPP_INFO_STREAM(
146 getLogger(), "[" << this->getName() << "] Sending goal to action server: "
147 << static_cast<const void *>(client.get()));
148
149 auto goalFuture = client->async_send_goal(goal, options);
150 {
151 std::lock_guard<std::mutex> lock(actionMutex_);
152 lastRequest_ = goalFuture;
153 }
154
155 return goalFuture;
156 }
157
159 {
160 // Same rule as sendGoal: the cancel call runs outside actionMutex_. A goal whose sendGoal is
161 // between its two lock scopes is not seen here; no caller cancels while another thread sends.
162 std::shared_ptr<ActionClient> client;
163 std::shared_future<typename GoalHandle::SharedPtr> request;
164 {
165 std::lock_guard<std::mutex> lock(actionMutex_);
166 if (client_ != nullptr && lastRequest_ && lastRequest_->valid())
167 {
168 client = client_;
169 request = *lastRequest_;
170 }
171 }
172
173 if (client == nullptr)
174 {
175 RCLCPP_WARN_STREAM(getLogger(), "[" << this->getName() << "] No active goal to cancel");
176 return false;
177 }
178
179 RCLCPP_INFO_STREAM(getLogger(), "[" << this->getName() << "] Cancelling current goal");
180
181 // Only the last goal is cancelled, never every goal of the server: the next state may already
182 // have sent its own through this component when the server processes the request.
183 std::shared_future<typename ActionClient::CancelResponse::SharedPtr> cancelFuture;
184 typename GoalHandle::SharedPtr goalHandle;
185 if (request.wait_for(std::chrono::seconds(0)) == std::future_status::ready)
186 {
187 goalHandle = request.get();
188 }
189 try
190 {
191 // A goal whose response has not arrived yet has no handle; it is cancelled by its send time.
192 cancelFuture = goalHandle != nullptr ? client->async_cancel_goal(goalHandle)
193 : client->async_cancel_goals_before(getNode()->now());
194 }
195 catch (const rclcpp_action::exceptions::UnknownGoalHandleError &)
196 {
197 RCLCPP_INFO_STREAM(getLogger(), "[" << this->getName() << "] The goal has already finished");
198 return false;
199 }
200 {
201 std::lock_guard<std::mutex> lock(actionMutex_);
202 lastCancelResponse_ = cancelFuture;
203 }
204 return true;
205 }
206
207 bool isServerReady() const { return client_ && client_->action_server_is_ready(); }
208
210 {
211 if (client_)
212 {
213 RCLCPP_INFO_STREAM(
214 getLogger(),
215 "[" << this->getName() << "] Waiting for action server: " << *actionServerName);
216 client_->wait_for_action_server();
217 }
218 }
219
220 // Component lifecycle
221 void onInitialize() override
222 {
223 if (!actionServerName)
224 {
225 RCLCPP_ERROR_STREAM(getLogger(), "[" << this->getName() << "] Action server name not set!");
226 return;
227 }
228
229 RCLCPP_INFO_STREAM(
230 getLogger(),
231 "[" << this->getName() << "] Initializing action client for: " << *actionServerName);
232
233 client_ = rclcpp_action::create_client<ActionType>(getNode(), *actionServerName);
234 RCLCPP_INFO_STREAM(
235 getLogger(),
236 "[" << this->getName() << "] DONE Initializing action client for: " << *actionServerName);
237
238 // Set up feedback callback
239 feedbackCallback_ = [this](auto goalHandle, auto feedback)
240 { this->onFeedback(goalHandle, feedback); };
241 }
242
243 template <typename TOrthogonal, typename TSourceObject>
245 {
246 // Event source type is THIS COMPONENT, not the owning client: the event
247 // payload type is TSource::WrappedResult, and typing it on the client would
248 // wrongly assume the client's WrappedResult typedef matches this component's
249 // action - which breaks as soon as a client owns action clients of more than
250 // one action type. Nothing in-tree listens to client-typed events from this
251 // component (domain interfaces like CpNav2ActionInterface post those).
252 postSuccessEvent = [this](const WrappedResult & result)
253 { this->postResultEvent<EvActionSucceeded<CpActionClient<ActionType>, TOrthogonal>>(result); };
254
255 postAbortedEvent = [this](const WrappedResult & result)
256 { this->postResultEvent<EvActionAborted<CpActionClient<ActionType>, TOrthogonal>>(result); };
257
258 postCancelledEvent = [this](const WrappedResult & result)
259 { this->postResultEvent<EvActionCancelled<CpActionClient<ActionType>, TOrthogonal>>(result); };
260
261 postFeedbackEvent = [this](const Feedback & feedback)
262 {
264 actionFeedbackEvent->feedbackMessage = feedback;
265 this->postEvent(actionFeedbackEvent);
266 RCLCPP_DEBUG(getLogger(), "[%s] FEEDBACK EVENT", this->getName().c_str());
267 };
268 }
269
270 // Signal connection methods
271 template <typename T>
272 smacc2::SmaccSignalConnection onSucceeded(void (T::*callback)(const WrappedResult &), T * object)
273 {
274 return this->getStateMachine()->createSignalConnection(onActionSucceeded_, callback, object);
275 }
276
277 template <typename T>
278 smacc2::SmaccSignalConnection onAborted(void (T::*callback)(const WrappedResult &), T * object)
279 {
280 return this->getStateMachine()->createSignalConnection(onActionAborted_, callback, object);
281 }
282
283 template <typename T>
284 smacc2::SmaccSignalConnection onCancelled(void (T::*callback)(const WrappedResult &), T * object)
285 {
286 return this->getStateMachine()->createSignalConnection(onActionCancelled_, callback, object);
287 }
288
289 template <typename T>
290 smacc2::SmaccSignalConnection onFeedback(void (T::*callback)(const Feedback &), T * object)
291 {
292 return this->getStateMachine()->createSignalConnection(onActionFeedback_, callback, object);
293 }
294
295 // Access to underlying client for advanced usage
296 std::shared_ptr<ActionClient> getActionClient() const { return client_; }
297
298private:
299 std::shared_ptr<ActionClient> client_ = nullptr;
300 std::optional<std::shared_future<typename GoalHandle::SharedPtr>> lastRequest_;
301 std::optional<
302 std::shared_future<typename rclcpp_action::Client<ActionType>::CancelResponse::SharedPtr>>
305 std::mutex actionMutex_;
306
308 typename GoalHandle::SharedPtr /* goalHandle */,
309 const std::shared_ptr<const Feedback> feedback_msg)
310 {
311 onActionFeedback_(*feedback_msg);
312 postFeedbackEvent(*feedback_msg);
313 }
314
315 void onResult(const WrappedResult & result_msg)
316 {
317 const auto & resultType = result_msg.code;
318
319 RCLCPP_INFO_STREAM(
320 getLogger(), "[" << this->getName() << "] Action result ["
321 << rclcpp_action::to_string(result_msg.goal_id) << "]: " << (int)resultType);
322
323 if (resultType == rclcpp_action::ResultCode::SUCCEEDED)
324 {
325 RCLCPP_INFO(getLogger(), "[%s] Action result: Success", this->getName().c_str());
326 onActionSucceeded_(result_msg);
327 postSuccessEvent(result_msg);
328 }
329 else if (resultType == rclcpp_action::ResultCode::ABORTED)
330 {
331 RCLCPP_INFO(getLogger(), "[%s] Action result: Aborted", this->getName().c_str());
332 onActionAborted_(result_msg);
333 postAbortedEvent(result_msg);
334 }
335 else if (resultType == rclcpp_action::ResultCode::CANCELED)
336 {
337 RCLCPP_INFO(getLogger(), "[%s] Action result: Cancelled", this->getName().c_str());
338 onActionCancelled_(result_msg);
339 postCancelledEvent(result_msg);
340 }
341 else
342 {
343 RCLCPP_WARN(
344 getLogger(), "[%s] Action result: Unhandled type: %d", this->getName().c_str(),
345 (int)resultType);
346 }
347 }
348
349 template <typename EvType>
350 void postResultEvent(const WrappedResult & result)
351 {
352 auto ev = smacc2::makeEvent<EvType>();
353 ev->resultMessage = result;
354 RCLCPP_INFO(
355 getLogger(), "[%s] Posting event: %s", this->getName().c_str(),
356 smacc2::demangleSymbol(typeid(ev.get()).name()).c_str());
357 this->postEvent(ev);
358 }
359};
360
361} // namespace client_core_components
362} // namespace smacc2
ISmaccStateMachine * getStateMachine()
virtual std::string getName() const
rclcpp::Logger getLogger() const
rclcpp::Node::SharedPtr getNode()
smacc2::SmaccSignalConnection createSignalConnection(TSmaccSignal &signal, TMemberFunctionPrototype callback, TSmaccObjectType *object)
std::function< void(std::shared_future< typename GoalHandle::SharedPtr >)> GoalResponseCallback
typename ActionClient::SendGoalOptions SendGoalOptions
std::function< void(const WrappedResult &)> postCancelledEvent
typename GoalHandle::WrappedResult WrappedResult
std::optional< std::shared_future< typename GoalHandle::SharedPtr > > lastRequest_
void onResult(const WrappedResult &result_msg)
smacc2::SmaccSignalConnection onSucceeded(void(T::*callback)(const WrappedResult &), T *object)
CpActionClient(const std::string &actionServerName)
std::shared_future< typename GoalHandle::SharedPtr > sendGoal(Goal &goal, typename smacc2::SmaccSignal< void(const WrappedResult &)>::WeakPtr resultCallback=typename smacc2::SmaccSignal< void(const WrappedResult &)>::WeakPtr())
smacc2::SmaccSignalConnection onFeedback(void(T::*callback)(const Feedback &), T *object)
smacc2::SmaccSignal< void(const WrappedResult &)> onActionCancelled_
smacc2::SmaccSignal< void(const Feedback &)> onActionFeedback_
std::function< void(const WrappedResult &)> postSuccessEvent
void postResultEvent(const WrappedResult &result)
typename GoalHandle::FeedbackCallback FeedbackCallback
smacc2::SmaccSignalConnection onAborted(void(T::*callback)(const WrappedResult &), T *object)
std::optional< std::chrono::milliseconds > serverTimeout
rclcpp_action::Client< ActionType > ActionClient
smacc2::SmaccSignalConnection onCancelled(void(T::*callback)(const WrappedResult &), T *object)
smacc2::SmaccSignal< void(const WrappedResult &)> onActionSucceeded_
void onFeedback(typename GoalHandle::SharedPtr, const std::shared_ptr< const Feedback > feedback_msg)
std::shared_ptr< ActionClient > getActionClient() const
std::function< void(const WrappedResult &)> postAbortedEvent
smacc2::SmaccSignal< void(const WrappedResult &)> onActionAborted_
std::function< void(const Feedback &)> postFeedbackEvent
typename GoalHandle::ResultCallback ResultCallback
rclcpp_action::ClientGoalHandle< ActionType > GoalHandle
std::optional< std::shared_future< typename rclcpp_action::Client< ActionType >::CancelResponse::SharedPtr > > lastCancelResponse_
std::string demangleSymbol()
boost::signals2::connection SmaccSignalConnection
boost::intrusive_ptr< EventType > makeEvent(Args &&... args)