SMACC2
Loading...
Searching...
No Matches
cp_waypoints_navigator.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 <tf2/transform_datatypes.h>
22#include <yaml-cpp/yaml.h>
23
24#include <algorithm>
25#include <ament_index_cpp/get_package_share_directory.hpp>
26#include <cl_nav2z/cl_nav2z.hpp>
27#include <cl_nav2z/common.hpp>
33#include <fstream>
34#include <rclcpp/rclcpp.hpp>
35
36namespace cl_nav2z
37{
38using namespace std::chrono_literals;
39using namespace smacc2;
40
41CpWaypointNavigatorBase::CpWaypointNavigatorBase() : currentWaypoint_(0), waypoints_(0) {}
42
44
46
48
50{
51 this->requiresComponent(nav2ActionInterface_, ComponentRequirement::HARD);
52}
53
61
69
72{
74 // asks whether the waypoint just reached is the last one, so before the index moves on
75 this->notifyGoalReached();
77 RCLCPP_WARN(
78 getLogger(), "[CpWaypointNavigator] Goal result received, incrementing waypoint index: %ld",
81
83}
84
86{
87 if (count <= 0) return;
88 currentWaypoint_ = std::max(currentWaypoint_ - count, 0L);
89}
90
92{
93 if (count <= 0) return;
94 // stops at the last waypoint; 0 when the list is empty
95 const long last = std::max(static_cast<long>(waypoints_.size()) - 1, 0L);
96 currentWaypoint_ = std::min(currentWaypoint_ + count, last);
97}
98
100{
101 const long count = static_cast<long>(waypoints_.size());
102 const long previousWaypoint = currentWaypoint_;
103 long found = -1;
104
105 // an empty name is that of an unnamed waypoint and matches nothing
106 if (!name.empty())
107 {
108 // forwards from the current waypoint first, then backwards from the one before it
109 for (long i = std::max(previousWaypoint, 0L); i < count && found < 0; i++)
110 {
111 if (waypointsNames_[i] == name) found = i;
112 }
113 for (long i = std::min(previousWaypoint, count) - 1; i >= 0 && found < 0; i--)
114 {
115 if (waypointsNames_[i] == name) found = i;
116 }
117 }
118
119 if (found < 0)
120 {
121 RCLCPP_WARN(
122 getLogger(),
123 "[CpWaypointNavigator] seekName(%s): no waypoint has that name, index left at %ld",
124 name.c_str(), currentWaypoint_);
125 return false;
126 }
127
128 currentWaypoint_ = found;
129 RCLCPP_INFO(
130 getLogger(), "[CpWaypointNavigator] seekName(%s), previous index: %ld, after index: %ld",
131 name.c_str(), previousWaypoint, currentWaypoint_);
132 return true;
133}
134
136 std::string parameter_name, std::string yaml_file_package_name)
137{
138 // if it is the first time and the waypoints navigator is not configured
139 std::string planfilepath;
140 // a second load of the same parameter must not declare it again
141 if (!getNode()->has_parameter(parameter_name))
142 {
143 getNode()->declare_parameter(parameter_name, planfilepath);
144 }
145 RCLCPP_INFO(getLogger(), "waypoints plan parameter: %s", planfilepath.c_str());
146 if (getNode()->get_parameter(parameter_name, planfilepath))
147 {
148 std::string package_share_directory =
149 ament_index_cpp::get_package_share_directory(yaml_file_package_name);
150
151 RCLCPP_INFO(getLogger(), "file macro path: %s", planfilepath.c_str());
152
153 boost::replace_all(planfilepath, "$(pkg_share)", package_share_directory);
154
155 RCLCPP_INFO(getLogger(), "package share path: %s", package_share_directory.c_str());
156 RCLCPP_INFO(getLogger(), "waypoints plan file: %s", planfilepath.c_str());
157
158 RCLCPP_INFO(getLogger(), "waypoints plan: %s", planfilepath.c_str());
159 return this->loadWayPointsFromFile(planfilepath);
160 }
161
162 RCLCPP_ERROR(getLogger(), "waypoints plan file not found: NONE");
163 return false;
164}
165
167{
168 if (succeededNav2ZClientConnection_.connected())
169 {
170 this->succeededNav2ZClientConnection_.disconnect();
171 this->cancelledNav2ZClientConnection_.disconnect();
172 this->abortedNav2ZClientConnection_.disconnect();
173 }
174}
175
176std::optional<std::shared_future<
177 std::shared_ptr<rclcpp_action::ClientGoalHandle<nav2_msgs::action::NavigateToPose>>>>
178CpWaypointNavigator::sendNextGoal(std::optional<NavigateNextWaypointOptions> options)
179{
180 if (currentWaypoint_ >= 0 && currentWaypoint_ < (int)waypoints_.size())
181 {
182 const auto & next = waypoints_[currentWaypoint_];
183
184 const std::string & nextName = waypointsNames_[currentWaypoint_];
185 if (!nextName.empty())
186 {
187 RCLCPP_INFO(
188 getLogger(), "[CpWaypointNavigator] sending goal, waypoint: %s", nextName.c_str());
189 }
190 else
191 {
192 RCLCPP_INFO(
193 getLogger(), "[CpWaypointNavigator] sending goal, waypoint: %ld", currentWaypoint_);
194 }
195
196 nav2_msgs::action::NavigateToPose::Goal goal;
197 CpPose * p = nullptr;
198 this->requiresComponent(p, ComponentRequirement::HARD);
199
200 // configuring goal
201 goal.pose.header.frame_id = p->getReferenceFrame();
202 goal.pose.pose = next;
203
204 cl_nav2z::CpPlannerSwitcher * plannerSwitcher = nullptr;
205 this->requiresComponent(plannerSwitcher, ComponentRequirement::HARD);
206
207 plannerSwitcher->setDefaultPlanners(false);
208 if (options && options->controllerName_)
209 {
210 RCLCPP_WARN(
211 getLogger(), "[WaypointsNavigator] override controller: %s",
212 options->controllerName_->c_str());
213
214 plannerSwitcher->setDesiredController(*options->controllerName_);
215 }
216 else
217 {
218 RCLCPP_WARN(getLogger(), "[WaypointsNavigator] Configuring default planners");
219 }
220
221 cl_nav2z::CpGoalCheckerSwitcher * goalCheckerSwitcher = nullptr;
222 this->requiresComponent(goalCheckerSwitcher, ComponentRequirement::SOFT);
223
224 if (goalCheckerSwitcher == nullptr)
225 {
226 RCLCPP_WARN(
227 getLogger(), "[WaypointsNavigator] no CpGoalCheckerSwitcher; goal checker left as is");
228 }
229 else if (options && options->goalCheckerName_)
230 {
231 RCLCPP_WARN(
232 getLogger(), "[WaypointsNavigator] override goal checker: %s",
233 options->goalCheckerName_->c_str());
234
235 goalCheckerSwitcher->setGoalCheckerId(*options->goalCheckerName_);
236 }
237 else
238 {
239 RCLCPP_WARN(getLogger(), "[WaypointsNavigator] Configuring default goal checker");
240 goalCheckerSwitcher->setGoalCheckerId("goal_checker");
241 }
242
243 plannerSwitcher->commitPublish();
244
245 RCLCPP_INFO(getLogger(), "[WaypointsNavigator] Getting odom tracker");
246
247 cl_nav2z::odom_tracker::CpOdomTracker * odomTracker = nullptr;
248 requiresComponent(odomTracker, ComponentRequirement::SOFT);
249
250 if (odomTracker != nullptr)
251 {
252 RCLCPP_INFO(getLogger(), "[WaypointsNavigator] Storing path in odom tracker");
253
254 auto pathname = this->owner_->getStateMachine()->getCurrentState()->getName() + " - " +
255 getName() + " - " + nextName;
256 odomTracker->pushPath(pathname);
257 // Stamped pose: the bare-Pose overload would mislabel these map-frame
258 // coordinates with the odom frame (see cb_navigate_global_position.cpp)
259 odomTracker->setStartPoint(p->toPoseStampedMsg());
261 }
262
263 // Set up navigation result handling
264 if (!succeededNav2ZClientConnection_.connected())
265 {
272 }
273
274 return nav2ActionInterface_->sendGoal(goal);
275 }
276 else
277 {
278 RCLCPP_WARN(
279 getLogger(),
280 "[CpWaypointsNavigator] All waypoints were consumed. There is no more waypoints available.");
281 }
282
283 return std::nullopt;
284}
285
287{
288 // the current waypoint is the one reached: when it is the last, post the finalization EOF event
289 if (currentWaypoint_ == (long)waypoints_.size() - 1)
290 {
291 RCLCPP_WARN(getLogger(), "[CpWaypointNavigator] Last waypoint reached, posting EOF event. ");
293 }
294}
295
298{
299 if (r.code == rclcpp_action::ResultCode::SUCCEEDED)
300 {
301 this->onGoalReached(r);
302 }
303 else if (r.code == rclcpp_action::ResultCode::CANCELED)
304 {
305 this->onGoalCancelled(r);
306 }
307 else
308 {
309 // ABORTED, and UNKNOWN treated the same way.
310 this->onGoalAborted(r);
311 }
312}
313
314void CpWaypointNavigatorBase::insertWaypoint(int index, geometry_msgs::msg::Pose & newpose)
315{
316 if (index >= 0 && index <= (int)waypoints_.size())
317 {
318 waypoints_.insert(waypoints_.begin() + index, newpose);
319 waypointsNames_.insert(waypointsNames_.begin() + index, std::string());
320 }
321}
322
324 const geometry_msgs::msg::Pose & pose, const std::string & name)
325{
326 waypoints_.push_back(pose);
327 waypointsNames_.push_back(name);
328}
329
331{
332 waypoints_.clear();
333 waypointsNames_.clear();
334}
335
336void CpWaypointNavigatorBase::setWaypoints(const std::vector<geometry_msgs::msg::Pose> & waypoints)
337{
339 for (const auto & pose : waypoints)
340 {
341 addWaypoint(pose, std::string());
342 }
343}
344
345void CpWaypointNavigatorBase::setWaypoints(const std::vector<Pose2D> & waypoints)
346{
348 int i = 0;
349 for (auto & p : waypoints)
350 {
351 geometry_msgs::msg::Pose pose;
352 pose.position.x = p.x_;
353 pose.position.y = p.y_;
354 pose.position.z = 0.0;
355 tf2::Quaternion q;
356 q.setRPY(0, 0, p.yaw_);
357 pose.orientation = tf2::toMsg(q);
358
359 addWaypoint(pose, std::to_string(i++));
360 }
361}
362
364{
365 if (index >= 0 && index < (int)waypoints_.size())
366 {
367 waypoints_.erase(waypoints_.begin() + index);
368 waypointsNames_.erase(waypointsNames_.begin() + index);
369 }
370}
371
372const std::vector<geometry_msgs::msg::Pose> & CpWaypointNavigatorBase::getWaypoints() const
373{
374 return waypoints_;
375}
376
377geometry_msgs::msg::Pose CpWaypointNavigatorBase::getPose(int index) const
378{
379 if (index >= 0 && index < (int)waypoints_.size())
380 {
381 return waypoints_[index];
382 }
383 else
384 {
385 throw std::out_of_range("Waypoint index out of range");
386 }
387}
388geometry_msgs::msg::Pose CpWaypointNavigatorBase::getCurrentPose() const
389{
390 if (currentWaypoint_ >= 0 && currentWaypoint_ < (int)waypoints_.size())
391 {
393 }
394 else
395 {
396 throw std::out_of_range("Waypoint index out of range");
397 }
398}
399
400std::optional<geometry_msgs::msg::Pose> CpWaypointNavigatorBase::getNamedPose(
401 std::string name) const
402{
403 // an empty name is that of an unnamed waypoint and matches nothing
404 if (!name.empty())
405 {
406 for (std::size_t i = 0; i < this->waypointsNames_.size(); i++)
407 {
408 if (this->waypointsNames_[i] == name)
409 {
410 return this->waypoints_[i];
411 }
412 }
413 }
414
415 return std::nullopt;
416}
417
418const std::vector<std::string> & CpWaypointNavigatorBase::getWaypointNames() const
419{
420 return waypointsNames_;
421}
422
423std::optional<std::string> CpWaypointNavigatorBase::getCurrentWaypointName() const
424{
425 if (
426 currentWaypoint_ >= 0 && currentWaypoint_ < (long)waypointsNames_.size() &&
428 {
430 }
431 return std::nullopt;
432}
433
435
436#define HAVE_NEW_YAMLCPP
438{
439 RCLCPP_INFO_STREAM(getLogger(), "[CpWaypointNavigatorBase] Loading file:" << filepath);
441 std::ifstream ifs(filepath.c_str(), std::ifstream::in);
442 if (ifs.good() == false)
443 {
444 RCLCPP_ERROR_STREAM(getLogger(), "Waypoints file not found: " << filepath);
445 return false;
446 }
447
448 try
449 {
450#ifdef HAVE_NEW_YAMLCPP
451 YAML::Node node = YAML::Load(ifs);
452#else
453 YAML::Parser parser(ifs);
454 parser.GetNextDocument(node);
455#endif
456
457#ifdef HAVE_NEW_YAMLCPP
458 const YAML::Node & wp_node_tmp = node["waypoints"];
459 const YAML::Node * wp_node = wp_node_tmp ? &wp_node_tmp : nullptr;
460#else
461 const YAML::Node * wp_node = node.FindValue("waypoints");
462#endif
463
464 if (wp_node != nullptr)
465 {
466 for (std::size_t i = 0; i < wp_node->size(); ++i)
467 {
468 // Parse waypoint entries on YAML
469 geometry_msgs::msg::Pose wp;
470
471 try
472 {
473 auto wpnodei = (*wp_node)[i];
474 wp.position.x = wpnodei["position"]["x"].as<double>();
475 wp.position.y = wpnodei["position"]["y"].as<double>();
476 wp.position.z = wpnodei["position"]["z"].as<double>();
477 wp.orientation.x = wpnodei["orientation"]["x"].as<double>();
478 wp.orientation.y = wpnodei["orientation"]["y"].as<double>();
479 wp.orientation.z = wpnodei["orientation"]["z"].as<double>();
480 wp.orientation.w = wpnodei["orientation"]["w"].as<double>();
481
482 addWaypoint(wp, wpnodei["name"].IsDefined() ? wpnodei["name"].as<std::string>() : "");
483 }
484 catch (...)
485 {
486 RCLCPP_ERROR(getLogger(), "parsing waypoint file, syntax error in point %ld", i);
487 }
488 }
489 RCLCPP_INFO_STREAM(getLogger(), "Parsed " << this->waypoints_.size() << " waypoints.");
490 }
491 else
492 {
493 RCLCPP_WARN_STREAM(getLogger(), "Couldn't find any waypoints in the provided yaml file.");
494 }
495 }
496 catch (const YAML::ParserException & ex)
497 {
498 RCLCPP_ERROR_STREAM(
499 getLogger(), "Error loading the Waypoints YAML file. Incorrect syntax: " << ex.what());
500 return false;
501 }
502 return true;
503}
504
506{
507 RCLCPP_INFO_STREAM(getLogger(), "[CpWaypointNavigator] Loading file:" << filepath);
509 std::ifstream ifs(filepath.c_str(), std::ifstream::in);
510 if (ifs.good() == false)
511 {
512 RCLCPP_ERROR_STREAM(getLogger(), "Waypoints file not found: " << filepath);
513 return false;
514 }
515
516 try
517 {
518#ifdef HAVE_NEW_YAMLCPP
519 YAML::Node node = YAML::Load(ifs);
520#else
521 YAML::Parser parser(ifs);
522 parser.GetNextDocument(node);
523#endif
524
525#ifdef HAVE_NEW_YAMLCPP
526 const YAML::Node & wp_node_tmp = node["waypoints"];
527 const YAML::Node * wp_node = wp_node_tmp ? &wp_node_tmp : nullptr;
528#else
529 const YAML::Node * wp_node = node.FindValue("waypoints");
530#endif
531
532 if (wp_node != nullptr)
533 {
534 for (std::size_t i = 0; i < wp_node->size(); ++i)
535 {
536 // Parse waypoint entries on YAML
537 geometry_msgs::msg::Pose wp;
538
539 try
540 {
541 wp.position.x = (*wp_node)[i]["x"].as<double>();
542 wp.position.y = (*wp_node)[i]["y"].as<double>();
543 auto name = (*wp_node)[i]["name"].as<std::string>();
544
545 addWaypoint(wp, name);
546 }
547 catch (...)
548 {
549 RCLCPP_ERROR(getLogger(), "parsing waypoint file, syntax error in point %ld", i);
550 }
551 }
552 RCLCPP_INFO_STREAM(getLogger(), "Parsed " << this->waypoints_.size() << " waypoints.");
553 }
554 else
555 {
556 RCLCPP_WARN_STREAM(getLogger(), "Couldn't find any waypoints in the provided yaml file.");
557 }
558 }
559 catch (const YAML::ParserException & ex)
560 {
561 RCLCPP_ERROR_STREAM(
562 getLogger(), "Error loading the Waypoints YAML file. Incorrect syntax: " << ex.what());
563 return false;
564 }
565 return true;
566}
567} // namespace cl_nav2z
void setGoalCheckerId(std::string goal_checker_id)
void setDefaultPlanners(bool commit=true)
geometry_msgs::msg::PoseStamped toPoseStampedMsg()
Definition cp_pose.hpp:66
const std::string & getReferenceFrame() const
Definition cp_pose.hpp:85
void setWaypoints(const std::vector< geometry_msgs::msg::Pose > &waypoints)
const std::vector< geometry_msgs::msg::Pose > & getWaypoints() const
bool loadWayPointsFromFile2(std::string filepath)
std::vector< geometry_msgs::msg::Pose > waypoints_
geometry_msgs::msg::Pose getCurrentPose() const
std::optional< std::string > getCurrentWaypointName() const
std::optional< geometry_msgs::msg::Pose > getNamedPose(std::string name) const
geometry_msgs::msg::Pose getPose(int index) const
bool loadWayPointsFromFile(std::string filepath)
void addWaypoint(const geometry_msgs::msg::Pose &pose, const std::string &name)
bool loadWaypointsFromYamlParameter(std::string parameter_name, std::string yaml_file_package_name)
const std::vector< std::string > & getWaypointNames() const
void insertWaypoint(int index, geometry_msgs::msg::Pose &newpose)
void onGoalReached(const components::CpNav2ActionInterface::WrappedResult &res)
smacc2::SmaccSignalConnection succeededNav2ZClientConnection_
smacc2::SmaccSignal< void()> onNavigationRequestSucceeded_
void onGoalAborted(const components::CpNav2ActionInterface::WrappedResult &)
smacc2::SmaccSignalConnection cancelledNav2ZClientConnection_
smacc2::SmaccSignalConnection abortedNav2ZClientConnection_
components::CpNav2ActionInterface * nav2ActionInterface_
smacc2::SmaccSignal< void()> onNavigationRequestCancelled_
void onNavigationResult(const components::CpNav2ActionInterface::WrappedResult &r)
void onGoalCancelled(const components::CpNav2ActionInterface::WrappedResult &)
std::optional< std::shared_future< std::shared_ptr< rclcpp_action::ClientGoalHandle< nav2_msgs::action::NavigateToPose > > > > sendNextGoal(std::optional< NavigateNextWaypointOptions > options=std::nullopt)
smacc2::SmaccSignal< void()> onNavigationRequestAborted_
smacc2::SmaccSignalConnection onNavigationSucceeded(void(T::*callback)(const WrappedResult &), T *object)
std::shared_future< typename GoalHandle::SharedPtr > sendGoal(Goal &goal)
smacc2::SmaccSignalConnection onNavigationAborted(void(T::*callback)(const WrappedResult &), T *object)
smacc2::SmaccSignalConnection onNavigationCancelled(void(T::*callback)(const WrappedResult &), T *object)
void setWorkingMode(WorkingMode workingMode)
void setStartPoint(const geometry_msgs::msg::PoseStamped &pose)
ISmaccStateMachine * getStateMachine()
ISmaccClient * owner_
Definition component.hpp:96
virtual std::string getName() const
rclcpp::Logger getLogger() const
void requiresComponent(TComponent *&requiredComponentStorage, ComponentRequirement requirementType=ComponentRequirement::SOFT)
rclcpp::Node::SharedPtr getNode()
virtual std::string getName()=0