SMACC2
Loading...
Searching...
No Matches
cb_action_client_behavior_base.hpp
Go to the documentation of this file.
1// Copyright 2026 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: Brett Aldrich, Pablo Inigo Blasco
18 *
19 ******************************************************************************************************************/
20
21#pragma once
22
23#include <atomic>
24#include <chrono>
25#include <future>
26#include <mutex>
27
30
31namespace smacc2
32{
33namespace client_behavior_bases
34{
35
36// Generic base for client behaviors that send one goal to a ROS 2 action server
37// (through a CpActionClient<TAction> component) and finish when the action
38// finishes. Derived behaviors fill a Goal in onEntry() and call sendGoal();
39// the base turns the action result into the state-scoped behavior events
40// EvCbSuccess<TDerived, TOrthogonal> / EvCbFailure<TDerived, TOrthogonal>.
41//
42// Lifecycle contract (see the async-thread locking rule in CLAUDE.md):
43// - components are resolved and result signals wired in
44// onStateOrthogonalAllocation, on the state machine thread. Never from the
45// asynchronous onEntry/onExit threads.
46// - a derived class that declares its own onStateOrthogonalAllocation MUST
47// chain to this one (and this one chains to SmaccAsyncClientBehavior's, which
48// installs the event-posting functions - skipping the chain leaves them empty
49// and postSuccessEvent() throws std::bad_function_call).
50// - no machine-scoped events are posted by this base: transition tables react
51// to the EvCb* behavior events, which cannot leak across state transitions.
52template <typename TAction>
54{
55public:
56 using Goal = typename TAction::Goal;
57 using GoalHandle = rclcpp_action::ClientGoalHandle<TAction>;
58 using WrappedResult = typename GoalHandle::WrappedResult;
59 using Feedback = typename TAction::Feedback;
61
62 template <typename TOrthogonal, typename TSourceObject>
87
89
90 // If the state exits while a goal is still in flight (e.g. a keyboard or
91 // timeout transition), cancel it: unlike bt_navigator navigation - where the
92 // next goal implicitly preempts - each behavior/docking server action keeps
93 // executing an abandoned goal, leaving the robot moving under a command
94 // nobody owns. Derived classes overriding onExit must chain to this.
95 void onExit() override
96 {
97 if (goalInFlight_)
98 {
99 RCLCPP_WARN(
100 getLogger(), "[%s] State exited with the action goal still in flight - cancelling",
101 getName().c_str());
102 cancelGoal();
103 }
104 }
105
106protected:
107 // Sends the goal and waits (in the calling asynchronous onEntry thread) for the
108 // server's goal response. Returns true if the goal was accepted. On a
109 // not-ready server, a rejected goal, or a response timeout it posts the
110 // failure event and returns false - the caller can simply return from
111 // onEntry(). This closes the silent-hang gap of a rejected/unanswered goal:
112 // CpActionClient installs no goal_response handling, and a rejected goal
113 // never invokes the result callback.
114 bool sendGoal(Goal & goal)
115 {
116 if (actionClient_ == nullptr || !actionClient_->isServerReady())
117 {
118 RCLCPP_ERROR(
119 getLogger(), "[%s] Action server not available, cannot send goal", getName().c_str());
120 this->postFailureEvent();
121 return false;
122 }
123
124 goalActivitySeen_ = false;
125 return this->trackGoal(actionClient_->sendGoal(goal));
126 }
127
128 // The second half of sendGoal(), for a goal that something else (a component) sent through the
129 // same action client: waits for the response and takes the goal's result as this behavior's own.
130 bool trackGoal(std::shared_future<typename GoalHandle::SharedPtr> goalHandleFuture)
131 {
132 {
133 std::lock_guard<std::mutex> lock(ownGoalMutex_);
134 ownGoalHandleFuture_ = goalHandleFuture;
135 }
136
137 // wait for goal acceptance in short slices so a state exit is honored
138 auto deadline = std::chrono::steady_clock::now() + goalResponseTimeout_;
139 while (!this->isShutdownRequested() && std::chrono::steady_clock::now() < deadline)
140 {
141 // Feedback or a result arriving proves the goal was accepted even if
142 // the goal-response future hasn't been serviced yet: under spin_some, a
143 // high-rate feedback stream (NavigateToPose feeds back continuously
144 // from acceptance) can starve the action client's response processing
145 // for the whole execution. Rejected goals produce no feedback, so their
146 // response resolves the future promptly.
148 {
149 goalInFlight_ = true;
150 return true;
151 }
152
153 if (goalHandleFuture.wait_for(std::chrono::milliseconds(50)) == std::future_status::ready)
154 {
155 if (goalHandleFuture.get() != nullptr)
156 {
157 goalInFlight_ = true; // accepted; the result signals will finish the behavior
158 return true;
159 }
160
161 RCLCPP_ERROR(getLogger(), "[%s] Goal was rejected by the action server", getName().c_str());
162 this->postFailureEvent();
163 return false;
164 }
165 }
166
167 if (!this->isShutdownRequested())
168 {
169 // No response, no feedback, no result within the window: ambiguous, and
170 // observed only under executor starvation with an accepted goal - a
171 // genuine rejection resolves the future in milliseconds. Assume the
172 // goal is running and let the result signals finish the behavior
173 // (fire-and-forget, the pre-template behavior), rather than failing a
174 // healthy mission.
175 RCLCPP_WARN(
176 getLogger(),
177 "[%s] No goal response from the action server after %ld ms; assuming the goal was "
178 "accepted (a rejection responds promptly) - result signals will finish this behavior",
179 getName().c_str(), static_cast<long>(goalResponseTimeout_.count()));
180 goalInFlight_ = true;
181 }
182 return true;
183 }
184
186 {
187 if (actionClient_ != nullptr)
188 {
190 }
191 }
192
193 // Result handlers connected by onStateOrthogonalAllocation. Base
194 // implementations record the result code and post the behavior events;
195 // derived classes may override to customize result handling.
196 virtual void onActionSuccess(const WrappedResult & result)
197 {
198 actionResult_ = result.code;
199 RCLCPP_INFO(getLogger(), "[%s] Action succeeded, propagating success event", getName().c_str());
200 this->postSuccessEvent();
201 }
202
203 virtual void onActionAbort(const WrappedResult & result)
204 {
205 actionResult_ = result.code;
206 RCLCPP_INFO(getLogger(), "[%s] Action failed, propagating failure event", getName().c_str());
207 this->postFailureEvent();
208 }
209
210 // optional: override to consume action feedback (distance traveled etc.)
211 virtual void onActionFeedback(const Feedback & /*feedback*/) {}
212
213 // set from the derived constructor to bind to a named CpActionClient
214 // instance; empty binds the first of matching type. Must be set before
215 // onStateOrthogonalAllocation runs (i.e. NOT in runtimeConfigure, which
216 // executes after allocation)
217 void setActionClientName(std::string name) { actionClientName_ = std::move(name); }
218
220 std::string actionClientName_;
221
222 rclcpp_action::ResultCode actionResult_ = rclcpp_action::ResultCode::UNKNOWN;
223
224 // how long sendGoal waits for the server to accept/reject the goal
225 std::chrono::milliseconds goalResponseTimeout_ = std::chrono::milliseconds(10000);
226
227private:
228 // trampolines wired to the component signals: clear the in-flight flag
229 // regardless of what a derived handler override does, then dispatch to the
230 // overridable virtuals
232 {
233 if (!isOwnGoal(result)) return;
234 goalActivitySeen_ = true;
235 goalInFlight_ = false;
236 this->onActionSuccess(result);
237 }
238
240 {
241 if (!isOwnGoal(result)) return;
242 goalActivitySeen_ = true;
243 goalInFlight_ = false;
244 this->onActionAbort(result);
245 }
246
247 void dispatchActionFeedback(const Feedback & feedback)
248 {
249 goalActivitySeen_ = true;
250 this->onActionFeedback(feedback);
251 }
252
253 // The component's result signals fire for every goal sent through it, so a result of the previous
254 // state's goal (typically its cancellation) can arrive while this behavior's own goal runs.
255 bool isOwnGoal(const WrappedResult & result)
256 {
257 std::shared_future<typename GoalHandle::SharedPtr> future;
258 {
259 std::lock_guard<std::mutex> lock(ownGoalMutex_);
260 future = ownGoalHandleFuture_;
261 }
262 // rclcpp_action resolves the goal response before it can deliver that goal's result.
263 const bool own = future.valid() &&
264 future.wait_for(std::chrono::seconds(0)) == std::future_status::ready &&
265 future.get() != nullptr && future.get()->get_goal_id() == result.goal_id;
266 if (!own)
267 {
268 RCLCPP_INFO(
269 getLogger(), "[%s] Ignoring the result of a goal this behavior did not send",
270 getName().c_str());
271 }
272 return own;
273 }
274
276 std::mutex ownGoalMutex_;
277 std::shared_future<typename GoalHandle::SharedPtr> ownGoalHandleFuture_;
278 std::atomic<bool> goalInFlight_{false};
279 std::atomic<bool> goalActivitySeen_{false};
280};
281
282} // namespace client_behavior_bases
283} // namespace smacc2
virtual rclcpp::Logger getLogger() const
void requiresComponent(SmaccComponentType *&storage, ComponentRequirement requirementType=ComponentRequirement::SOFT)
bool isShutdownRequested()
onEntry is executed in a new thread. However the current state cannot be left until the onEntry threa...
std::shared_future< typename GoalHandle::SharedPtr > ownGoalHandleFuture_
bool trackGoal(std::shared_future< typename GoalHandle::SharedPtr > goalHandleFuture)
smacc2::SmaccSignalConnection onSucceeded(void(T::*callback)(const WrappedResult &), T *object)
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::SmaccSignalConnection onAborted(void(T::*callback)(const WrappedResult &), T *object)
smacc2::SmaccSignalConnection onCancelled(void(T::*callback)(const WrappedResult &), T *object)