moveit2
The MoveIt Motion Planning Framework for ROS 2.
global_planner_component.cpp
Go to the documentation of this file.
1 /*********************************************************************
2  * Software License Agreement (BSD License)
3  *
4  * Copyright (c) 2020, PickNik Inc.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * * Redistributions of source code must retain the above copyright
12  * notice, this list of conditions and the following disclaimer.
13  * * Redistributions in binary form must reproduce the above
14  * copyright notice, this list of conditions and the following
15  * disclaimer in the documentation and/or other materials provided
16  * with the distribution.
17  * * Neither the name of PickNik Inc. nor the names of its
18  * contributors may be used to endorse or promote products derived
19  * from this software without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
25  * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
27  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
29  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
31  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32  * POSSIBILITY OF SUCH DAMAGE.
33  *********************************************************************/
34 
38 #include <moveit_msgs/msg/move_it_error_codes.hpp>
39 
40 #include <chrono>
41 #include <thread>
42 
43 namespace
44 {
45 const rclcpp::Logger LOGGER = rclcpp::get_logger("global_planner_component");
46 const auto JOIN_THREAD_TIMEOUT = std::chrono::seconds(1);
47 } // namespace
48 
50 {
51 using namespace std::chrono_literals;
52 const std::string UNDEFINED = "<undefined>";
53 
55  : node_{ std::make_shared<rclcpp::Node>("global_planner_component", options) }
56 {
57  if (!initializeGlobalPlanner())
58  {
59  throw std::runtime_error("Failed to initialize Global Planner Component");
60  }
61 }
62 
63 bool GlobalPlannerComponent::initializeGlobalPlanner()
64 {
65  // Initialize global planning request action server
66  std::string global_planning_action_name = "";
67  node_->declare_parameter("global_planning_action_name", "");
68  node_->get_parameter<std::string>("global_planning_action_name", global_planning_action_name);
69  if (global_planning_action_name.empty())
70  {
71  RCLCPP_ERROR(LOGGER, "global_planning_action_name was not defined");
72  return false;
73  }
74  cb_group_ = node_->create_callback_group(rclcpp::CallbackGroupType::MutuallyExclusive);
75  global_planning_request_server_ = rclcpp_action::create_server<moveit_msgs::action::GlobalPlanner>(
76  node_, global_planning_action_name,
77  // Goal callback
78  [this](const rclcpp_action::GoalUUID& /*unused*/,
79  const std::shared_ptr<const moveit_msgs::action::GlobalPlanner::Goal>& /*unused*/) {
80  RCLCPP_INFO(LOGGER, "Received global planning goal request");
81  // If another goal is active, cancel it and reject this goal
82  if (long_callback_thread_.joinable())
83  {
84  // Try to terminate the execution thread
85  auto future = std::async(std::launch::async, &std::thread::join, &long_callback_thread_);
86  if (future.wait_for(JOIN_THREAD_TIMEOUT) == std::future_status::timeout)
87  {
88  RCLCPP_WARN(LOGGER, "Another goal was running. Rejecting the new hybrid planning goal.");
89  return rclcpp_action::GoalResponse::REJECT;
90  }
91  if (!global_planner_instance_->reset())
92  {
93  throw std::runtime_error("Failed to reset the global planner while aborting current global planning");
94  }
95  }
96  return rclcpp_action::GoalResponse::ACCEPT_AND_EXECUTE;
97  },
98  // Cancel callback
99  [this](const std::shared_ptr<rclcpp_action::ServerGoalHandle<moveit_msgs::action::GlobalPlanner>>& /*unused*/) {
100  RCLCPP_INFO(LOGGER, "Received request to cancel global planning goal");
101  if (long_callback_thread_.joinable())
102  {
103  long_callback_thread_.join();
104  }
105  if (!global_planner_instance_->reset())
106  {
107  throw std::runtime_error("Failed to reset the global planner while aborting current global planning");
108  }
109  return rclcpp_action::CancelResponse::ACCEPT;
110  },
111  // Execution callback
112  [this](std::shared_ptr<rclcpp_action::ServerGoalHandle<moveit_msgs::action::GlobalPlanner>> goal_handle) {
113  // this needs to return quickly to avoid blocking the executor, so spin up a new thread
114  if (long_callback_thread_.joinable())
115  {
116  long_callback_thread_.join();
117  global_planner_instance_->reset();
118  }
119  long_callback_thread_ = std::thread(&GlobalPlannerComponent::globalPlanningRequestCallback, this, goal_handle);
120  },
121  rcl_action_server_get_default_options(), cb_group_);
122 
123  global_trajectory_pub_ = node_->create_publisher<moveit_msgs::msg::MotionPlanResponse>("global_trajectory", 1);
124 
125  // Load global planner plugin
126  planner_plugin_name_ = node_->declare_parameter<std::string>("global_planner_name", UNDEFINED);
127 
128  try
129  {
130  global_planner_plugin_loader_ = std::make_unique<pluginlib::ClassLoader<GlobalPlannerInterface>>(
131  "moveit_hybrid_planning", "moveit::hybrid_planning::GlobalPlannerInterface");
132  }
133  catch (pluginlib::PluginlibException& ex)
134  {
135  RCLCPP_ERROR(LOGGER, "Exception while creating global planner plugin loader: '%s'", ex.what());
136  return false;
137  }
138  try
139  {
140  global_planner_instance_ = global_planner_plugin_loader_->createUniqueInstance(planner_plugin_name_);
141  }
142  catch (pluginlib::PluginlibException& ex)
143  {
144  RCLCPP_ERROR(LOGGER, "Exception while loading global planner '%s': '%s'", planner_plugin_name_.c_str(), ex.what());
145  return false;
146  }
147 
148  // Initialize global planner plugin
149  if (!global_planner_instance_->initialize(node_))
150  {
151  RCLCPP_ERROR(LOGGER, "Unable to initialize global planner plugin '%s'", planner_plugin_name_.c_str());
152  return false;
153  }
154  RCLCPP_INFO(LOGGER, "Using global planner plugin '%s'", planner_plugin_name_.c_str());
155  return true;
156 }
157 
158 void GlobalPlannerComponent::globalPlanningRequestCallback(
159  const std::shared_ptr<rclcpp_action::ServerGoalHandle<moveit_msgs::action::GlobalPlanner>>& goal_handle)
160 {
161  // Plan global trajectory
162  moveit_msgs::msg::MotionPlanResponse planning_solution = global_planner_instance_->plan(goal_handle);
163 
164  // Send action response
165  auto result = std::make_shared<moveit_msgs::action::GlobalPlanner::Result>();
166  result->response = planning_solution;
167 
168  if (planning_solution.error_code.val == moveit_msgs::msg::MoveItErrorCodes::SUCCESS)
169  {
170  // Publish global planning solution to the local planner
171  global_trajectory_pub_->publish(planning_solution);
172  goal_handle->succeed(result);
173  }
174  else
175  {
176  goal_handle->abort(result);
177  }
178 
179  // Reset the global planner
180  global_planner_instance_->reset();
181 };
182 } // namespace moveit::hybrid_planning
183 
184 // Register the component with class_loader
185 #include <rclcpp_components/register_node_macro.hpp>
186 RCLCPP_COMPONENTS_REGISTER_NODE(moveit::hybrid_planning::GlobalPlannerComponent)
GlobalPlannerComponent(const rclcpp::NodeOptions &options)
Constructor.
const rclcpp::Logger LOGGER
Definition: async_test.h:31