一、概述

  目测是全网最全的解析,花了几个小时通读并整理的,供大家参考学习。

  概况的话可以看下古月居 https://www.guyuehome.com/270,其实它是翻译官方的,英语ok的可以去ros wiki翻看原版。 

  重点:navfn包 全局规划(Dji算法)、base_local_planner包 局部规划(Trajectory Rollout 和Dynamic Window approaches算法)

二、move_base.h

  1. #ifndef NAV_MOVE_BASE_ACTION_H_
  2. #define NAV_MOVE_BASE_ACTION_H_
  3.  
  4. #include <vector>
  5. #include <string>
  6.  
  7. #include <ros/ros.h>
  8.  
  9. #include <actionlib/server/simple_action_server.h>
  10. #include <move_base_msgs/MoveBaseAction.h>
  11.  
  12. #include <nav_core/base_local_planner.h>
  13. #include <nav_core/base_global_planner.h>
  14. #include <nav_core/recovery_behavior.h>
  15. #include <geometry_msgs/PoseStamped.h>
  16. #include <costmap_2d/costmap_2d_ros.h>
  17. #include <costmap_2d/costmap_2d.h>
  18. #include <nav_msgs/GetPlan.h>
  19.  
  20. #include <pluginlib/class_loader.hpp>
  21. #include <std_srvs/Empty.h>
  22.  
  23. #include <dynamic_reconfigure/server.h>
  24. #include "move_base/MoveBaseConfig.h"
  25.  
  26. namespace move_base {
  27. //声明server端,消息类型是move_base_msgs::MoveBaseAction
  28. typedef actionlib::SimpleActionServer<move_base_msgs::MoveBaseAction> MoveBaseActionServer;
  29. //movebase状态表示
  30. enum MoveBaseState {
  31. PLANNING,
  32. CONTROLLING,
  33. CLEARING
  34. };
  35. //触发恢复模式
  36. enum RecoveryTrigger
  37. {
  38. PLANNING_R,
  39. CONTROLLING_R,
  40. OSCILLATION_R
  41. };
  42.  
  43. //使用actionlib::ActionServer接口的类,该接口将robot移动到目标位置。
  44. class MoveBase {
  45. public:
  46. // 构造函数,传入的参数是tf
  47. MoveBase(tf2_ros::Buffer& tf);
  48.  
  49. //析构函数
  50. virtual ~MoveBase();
  51.  
  52. //控制闭环、全局规划、 到达目标返回true,没有到达返回false
  53. bool executeCycle(geometry_msgs::PoseStamped& goal, std::vector<geometry_msgs::PoseStamped>& global_plan);
  54.  
  55. private:
  56. /**
  57. * @brief 清除costmap的server端
  58. * @param req 表示server的request
  59. * @param resp 表示server的response
  60. * @return 如果server端被成功调用则为True,否则false
  61. */
  62. bool clearCostmapsService(std_srvs::Empty::Request &req, std_srvs::Empty::Response &resp);
  63.  
  64. /**
  65. * @brief 当action不活跃时,调用此函数,返回plan
  66. * @param req 表示goal的request
  67. * @param resp 表示plan的request
  68. * @return 规划成功返回reue,否则返回false
  69. */
  70. bool planService(nav_msgs::GetPlan::Request &req, nav_msgs::GetPlan::Response &resp);
  71.  
  72. /**
  73. * @brief 新的全局规划
  74. * @param goal 规划的目标点
  75. * @param plan 规划
  76. * @return 规划成功则返回True 否则false
  77. */
  78. bool makePlan(const geometry_msgs::PoseStamped& goal, std::vector<geometry_msgs::PoseStamped>& plan);
  79.  
  80. /**
  81. * @brief 从参数服务器加载导航参数Load the recovery behaviors
  82. * @param node 表示 ros::NodeHandle 加载的参数
  83. * @return 加载成功返回True 否则 false
  84. */
  85. bool loadRecoveryBehaviors(ros::NodeHandle node);
  86.  
  87. // 加载默认导航参数
  88. void loadDefaultRecoveryBehaviors();
  89.  
  90. /**
  91. * @brief 清楚机器人局部规划框的障碍物
  92. * @param size_x 局部规划框的长x
  93. * @param size_y 局部规划框的宽y
  94. */
  95. void clearCostmapWindows(double size_x, double size_y);
  96.  
  97. //发布速度为0的指令
  98. void publishZeroVelocity();
  99.  
  100. // 重置move_base action的状态,设置速度为0
  101. void resetState();
  102.  
  103. void goalCB(const geometry_msgs::PoseStamped::ConstPtr& goal);
  104.  
  105. void planThread();
  106.  
  107. void executeCb(const move_base_msgs::MoveBaseGoalConstPtr& move_base_goal);
  108.  
  109. bool isQuaternionValid(const geometry_msgs::Quaternion& q);
  110.  
  111. bool getRobotPose(geometry_msgs::PoseStamped& global_pose, costmap_2d::Costmap2DROS* costmap);
  112.  
  113. double distance(const geometry_msgs::PoseStamped& p1, const geometry_msgs::PoseStamped& p2);
  114.  
  115. geometry_msgs::PoseStamped goalToGlobalFrame(const geometry_msgs::PoseStamped& goal_pose_msg);
  116.  
  117. //周期性地唤醒规划器
  118. void wakePlanner(const ros::TimerEvent& event);
  119.  
  120. tf2_ros::Buffer& tf_;
  121.  
  122. MoveBaseActionServer* as_; //就是actionlib的server端
  123.  
  124. boost::shared_ptr<nav_core::BaseLocalPlanner> tc_;//局部规划器,加载并创建实例后的指针
  125. costmap_2d::Costmap2DROS* planner_costmap_ros_, *controller_costmap_ros_;//costmap的实例化指针
  126.  
  127. boost::shared_ptr<nav_core::BaseGlobalPlanner> planner_;//全局规划器,加载并创建实例后的指针
  128. std::string robot_base_frame_, global_frame_;
  129.  
  130. std::vector<boost::shared_ptr<nav_core::RecoveryBehavior> > recovery_behaviors_;//可能是出错后的恢复
  131. unsigned int recovery_index_;
  132.  
  133. geometry_msgs::PoseStamped global_pose_;
  134. double planner_frequency_, controller_frequency_, inscribed_radius_, circumscribed_radius_;
  135. double planner_patience_, controller_patience_;
  136. int32_t max_planning_retries_;
  137. uint32_t planning_retries_;
  138. double conservative_reset_dist_, clearing_radius_;
  139. ros::Publisher current_goal_pub_, vel_pub_, action_goal_pub_;
  140. ros::Subscriber goal_sub_;
  141. ros::ServiceServer make_plan_srv_, clear_costmaps_srv_;
  142. bool shutdown_costmaps_, clearing_rotation_allowed_, recovery_behavior_enabled_;
  143. double oscillation_timeout_, oscillation_distance_;
  144.  
  145. MoveBaseState state_;
  146. RecoveryTrigger recovery_trigger_;
  147.  
  148. ros::Time last_valid_plan_, last_valid_control_, last_oscillation_reset_;
  149. geometry_msgs::PoseStamped oscillation_pose_;
  150. pluginlib::ClassLoader<nav_core::BaseGlobalPlanner> bgp_loader_;
  151. pluginlib::ClassLoader<nav_core::BaseLocalPlanner> blp_loader_;
  152. pluginlib::ClassLoader<nav_core::RecoveryBehavior> recovery_loader_;
  153.  
  154. //触发哪种规划器
  155. std::vector<geometry_msgs::PoseStamped>* planner_plan_;//保存最新规划的路径,传给latest_plan_
  156. std::vector<geometry_msgs::PoseStamped>* latest_plan_;//在executeCycle中传给controller_plan_
  157. std::vector<geometry_msgs::PoseStamped>* controller_plan_;
  158.  
  159. //规划器线程
  160. bool runPlanner_;
  161. boost::recursive_mutex planner_mutex_;
  162. boost::condition_variable_any planner_cond_;
  163. geometry_msgs::PoseStamped planner_goal_;
  164. boost::thread* planner_thread_;
  165.  
  166. boost::recursive_mutex configuration_mutex_;
  167. dynamic_reconfigure::Server<move_base::MoveBaseConfig> *dsrv_;
  168.  
  169. void reconfigureCB(move_base::MoveBaseConfig &config, uint32_t level);
  170.  
  171. move_base::MoveBaseConfig last_config_;
  172. move_base::MoveBaseConfig default_config_;
  173. bool setup_, p_freq_change_, c_freq_change_;
  174. bool new_global_plan_;
  175. };
  176. };
  177. #endif

三、move_base_node.cpp

  1. #include <move_base/move_base.h>
  2. #include <tf2_ros/transform_listener.h>
  3.  
  4. int main(int argc, char** argv){
  5. ros::init(argc, argv, "move_base_node");
  6. tf2_ros::Buffer buffer(ros::Duration());
  7. tf2_ros::TransformListener tf(buffer);
  8.  
  9. move_base::MoveBase move_base( buffer );//本cpp中只调用了这个构造函数
  10.  
  11. //ros::MultiThreadedSpinner s;
  12. ros::spin();
  13.  
  14. return();
  15. }

四、move_base.cpp

  1. #include <move_base/move_base.h>
  2. #include <cmath>
  3.  
  4. #include <boost/algorithm/string.hpp>
  5. #include <boost/thread.hpp>
  6.  
  7. #include <geometry_msgs/Twist.h>
  8.  
  9. #include <tf2_geometry_msgs/tf2_geometry_msgs.h>
  10.  
  11. namespace move_base {
  12.  
  13. MoveBase::MoveBase(tf2_ros::Buffer& tf) :
  14. tf_(tf),
  15. as_(NULL),
  16. planner_costmap_ros_(NULL), controller_costmap_ros_(NULL),
  17. bgp_loader_("nav_core", "nav_core::BaseGlobalPlanner"),
  18. blp_loader_("nav_core", "nav_core::BaseLocalPlanner"),
  19. recovery_loader_("nav_core", "nav_core::RecoveryBehavior"),
  20. planner_plan_(NULL), latest_plan_(NULL), controller_plan_(NULL),
  21. runPlanner_(false), setup_(false), p_freq_change_(false), c_freq_change_(false), new_global_plan_(false) {
  22.  
  23. //1. 创建move_base action,绑定回调函数。定义一个名为move_base的SimpleActionServer。该服务器的Callback为MoveBase::executeCb。
  24. as_ = new MoveBaseActionServer(ros::NodeHandle(), "move_base", boost::bind(&MoveBase::executeCb, this, _1), false);
  25.  
  26. ros::NodeHandle private_nh("~");
  27. ros::NodeHandle nh;
  28.  
  29. recovery_trigger_ = PLANNING_R;
  30.  
  31. //2.加载参数。从参数服务器获取一些参数,包括两个规划器名称、代价地图坐标系、规划频率、控制周期等
  32. std::string global_planner, local_planner;
  33. private_nh.param("base_global_planner", global_planner, std::string("navfn/NavfnROS"));
  34. private_nh.param("base_local_planner", local_planner, std::string("base_local_planner/TrajectoryPlannerROS"));
  35. private_nh.param("global_costmap/robot_base_frame", robot_base_frame_, std::string("base_link"));
  36. private_nh.param("global_costmap/global_frame", global_frame_, std::string("map"));
  37. private_nh.param("planner_frequency", planner_frequency_, 0.0);
  38. private_nh.param("controller_frequency", controller_frequency_, 20.0);
  39. private_nh.param("planner_patience", planner_patience_, 5.0);
  40. private_nh.param("controller_patience", controller_patience_, 15.0);
  41. private_nh.param("max_planning_retries", max_planning_retries_, -); // disabled by default
  42.  
  43. private_nh.param("oscillation_timeout", oscillation_timeout_, 0.0);
  44. private_nh.param("oscillation_distance", oscillation_distance_, 0.5);
  45.  
  46. //set up plan triple buffer
  47. planner_plan_ = new std::vector<geometry_msgs::PoseStamped>();
  48. latest_plan_ = new std::vector<geometry_msgs::PoseStamped>();
  49. controller_plan_ = new std::vector<geometry_msgs::PoseStamped>();
  50.  
  51. //3. 设置规划器线程
  52. //set up the planner's thread
  53. planner_thread_ = new boost::thread(boost::bind(&MoveBase::planThread, this));
  54.  
  55. //4. 创建发布者
  56. //for commanding the base
  57. vel_pub_ = nh.advertise<geometry_msgs::Twist>("cmd_vel", );
  58. current_goal_pub_ = private_nh.advertise<geometry_msgs::PoseStamped>("current_goal", );
  59.  
  60. ros::NodeHandle action_nh("move_base");
  61. action_goal_pub_ = action_nh.advertise<move_base_msgs::MoveBaseActionGoal>("goal", );
  62.  
  63. //提供消息类型为geometry_msgs::PoseStamped的发送goals的接口,比如cb为MoveBase::goalCB,在rviz中输入的目标点就是通过这个函数来响应的
  64. ros::NodeHandle simple_nh("move_base_simple");
  65. goal_sub_ = simple_nh.subscribe<geometry_msgs::PoseStamped>("goal", , boost::bind(&MoveBase::goalCB, this, _1));
  66.  
  67. //我们假设机器人的半径与costmap的规定一致
  68. private_nh.param("local_costmap/inscribed_radius", inscribed_radius_, 0.325);
  69. private_nh.param("local_costmap/circumscribed_radius", circumscribed_radius_, 0.46);
  70. private_nh.param("clearing_radius", clearing_radius_, circumscribed_radius_);
  71. private_nh.param("conservative_reset_dist", conservative_reset_dist_, 3.0);
  72.  
  73. private_nh.param("shutdown_costmaps", shutdown_costmaps_, false);
  74. private_nh.param("clearing_rotation_allowed", clearing_rotation_allowed_, true);
  75. private_nh.param("recovery_behavior_enabled", recovery_behavior_enabled_, true);
  76.  
  77. // 5. 设置全局路径规划器
  78. //create the ros wrapper for the planner's costmap... and initializer a pointer we'll use with the underlying map
  79. planner_costmap_ros_ = new costmap_2d::Costmap2DROS("global_costmap", tf_);
  80. planner_costmap_ros_->pause();
  81.  
  82. //initialize the global planner
  83. try {
  84. planner_ = bgp_loader_.createInstance(global_planner);
  85. planner_->initialize(bgp_loader_.getName(global_planner), planner_costmap_ros_);
  86. } catch (const pluginlib::PluginlibException& ex) {
  87. ROS_FATAL("Failed to create the %s planner, are you sure it is properly registered and that the containing library is built? Exception: %s", global_planner.c_str(), ex.what());
  88. exit();
  89. }
  90.  
  91. // 6.设置局部路径规划器
  92. //create the ros wrapper for the controller's costmap... and initializer a pointer we'll use with the underlying map
  93. controller_costmap_ros_ = new costmap_2d::Costmap2DROS("local_costmap", tf_);
  94. controller_costmap_ros_->pause();
  95.  
  96. //create a local planner
  97. try {
  98. tc_ = blp_loader_.createInstance(local_planner);
  99. ROS_INFO("Created local_planner %s", local_planner.c_str());
  100. tc_->initialize(blp_loader_.getName(local_planner), &tf_, controller_costmap_ros_);
  101. } catch (const pluginlib::PluginlibException& ex) {
  102. ROS_FATAL("Failed to create the %s planner, are you sure it is properly registered and that the containing library is built? Exception: %s", local_planner.c_str(), ex.what());
  103. exit();
  104. }
  105.  
  106. // Start actively updating costmaps based on sensor data
  107.  
  108. //7.开始更新costmap
  109. planner_costmap_ros_->start();
  110. controller_costmap_ros_->start();
  111.  
  112. //advertise a service for getting a plan
  113. //8.开启创建地图,清除地图服务
  114. make_plan_srv_ = private_nh.advertiseService("make_plan", &MoveBase::planService, this);
  115.  
  116. //定义一个名为clear_costmaps的服务,cb为MoveBase::clearCostmapsService
  117. clear_costmaps_srv_ = private_nh.advertiseService("clear_costmaps", &MoveBase::clearCostmapsService, this);
  118.  
  119. //如果不小心关闭了costmap
  120. if(shutdown_costmaps_){
  121. ROS_DEBUG_NAMED("move_base","Stopping costmaps initially");
  122. planner_costmap_ros_->stop();
  123. controller_costmap_ros_->stop();
  124. }
  125.  
  126. //9.加载指定的恢复器
  127. if(!loadRecoveryBehaviors(private_nh)){
  128. loadDefaultRecoveryBehaviors();//先loadRecoveryBehaviors,不行再loadDefaultRecoveryBehaviors加载默认的,这里包括了找不到路自转360
  129. }
  130.  
  131. //initially, we'll need to make a plan
  132. state_ = PLANNING;
  133.  
  134. //we'll start executing recovery behaviors at the beginning of our list
  135. recovery_index_ = ;
  136.  
  137. //10.开启move_base动作器
  138. as_->start();
  139. //启动动态参数服务器,回调函数为reconfigureCB,推荐看一下古月居https://www.guyuehome.com/1173
  140. dsrv_ = new dynamic_reconfigure::Server<move_base::MoveBaseConfig>(ros::NodeHandle("~"));
  141. dynamic_reconfigure::Server<move_base::MoveBaseConfig>::CallbackType cb = boost::bind(&MoveBase::reconfigureCB, this, _1, _2);
  142. dsrv_->setCallback(cb);
  143. }
  144.  
  145. void MoveBase::reconfigureCB(move_base::MoveBaseConfig &config, uint32_t level){
  146. boost::recursive_mutex::scoped_lock l(configuration_mutex_);
  147.  
  148. //一旦被调用,我们要确保有原始配置
  149. if(!setup_)
  150. {
  151. last_config_ = config;
  152. default_config_ = config;
  153. setup_ = true;
  154. return;
  155. }
  156.  
  157. if(config.restore_defaults) {
  158. config = default_config_;
  159. //如果有人在参数服务器上设置默认值,要防止循环
  160. config.restore_defaults = false;
  161. }
  162.  
  163. if(planner_frequency_ != config.planner_frequency)
  164. {
  165. planner_frequency_ = config.planner_frequency;
  166. p_freq_change_ = true;
  167. }
  168.  
  169. if(controller_frequency_ != config.controller_frequency)
  170. {
  171. controller_frequency_ = config.controller_frequency;
  172. c_freq_change_ = true;
  173. }
  174.  
  175. planner_patience_ = config.planner_patience;
  176. controller_patience_ = config.controller_patience;
  177. max_planning_retries_ = config.max_planning_retries;
  178. conservative_reset_dist_ = config.conservative_reset_dist;
  179.  
  180. recovery_behavior_enabled_ = config.recovery_behavior_enabled;
  181. clearing_rotation_allowed_ = config.clearing_rotation_allowed;
  182. shutdown_costmaps_ = config.shutdown_costmaps;
  183.  
  184. oscillation_timeout_ = config.oscillation_timeout;
  185. oscillation_distance_ = config.oscillation_distance;
  186. if(config.base_global_planner != last_config_.base_global_planner) {
  187. boost::shared_ptr<nav_core::BaseGlobalPlanner> old_planner = planner_;
  188. //创建全局规划
  189. ROS_INFO("Loading global planner %s", config.base_global_planner.c_str());
  190. try {
  191. planner_ = bgp_loader_.createInstance(config.base_global_planner);
  192.  
  193. // 等待当前规划结束
  194. boost::unique_lock<boost::recursive_mutex> lock(planner_mutex_);
  195.  
  196. // 在新规划开始前clear旧的
  197. planner_plan_->clear();
  198. latest_plan_->clear();
  199. controller_plan_->clear();
  200. resetState();
  201. planner_->initialize(bgp_loader_.getName(config.base_global_planner), planner_costmap_ros_);
  202.  
  203. lock.unlock();
  204. } catch (const pluginlib::PluginlibException& ex) {
  205. ROS_FATAL("Failed to create the %s planner, are you sure it is properly registered and that the \
  206. containing library is built? Exception: %s", config.base_global_planner.c_str(), ex.what());
  207. planner_ = old_planner;
  208. config.base_global_planner = last_config_.base_global_planner;
  209. }
  210. }
  211.  
  212. if(config.base_local_planner != last_config_.base_local_planner){
  213. boost::shared_ptr<nav_core::BaseLocalPlanner> old_planner = tc_;
  214. //创建局部规划
  215. try {
  216. tc_ = blp_loader_.createInstance(config.base_local_planner);
  217. // 清理旧的
  218. planner_plan_->clear();
  219. latest_plan_->clear();
  220. controller_plan_->clear();
  221. resetState();
  222. tc_->initialize(blp_loader_.getName(config.base_local_planner), &tf_, controller_costmap_ros_);
  223. } catch (const pluginlib::PluginlibException& ex) {
  224. ROS_FATAL("Failed to create the %s planner, are you sure it is properly registered and that the \
  225. containing library is built? Exception: %s", config.base_local_planner.c_str(), ex.what());
  226. tc_ = old_planner;
  227. config.base_local_planner = last_config_.base_local_planner;
  228. }
  229. }
  230.  
  231. last_config_ = config;
  232. }
  233.  
  234. //为rviz等提供调用借口,将geometry_msgs::PoseStamped形式的goal转换成move_base_msgs::MoveBaseActionGoal,再发布到对应类型的goal话题中
  235. void MoveBase::goalCB(const geometry_msgs::PoseStamped::ConstPtr& goal){
  236. ROS_DEBUG_NAMED("move_base","In ROS goal callback, wrapping the PoseStamped in the action message and re-sending to the server.");
  237. move_base_msgs::MoveBaseActionGoal action_goal;
  238. action_goal.header.stamp = ros::Time::now();
  239. action_goal.goal.target_pose = *goal;
  240.  
  241. action_goal_pub_.publish(action_goal);
  242. }
  243.  
  244. void MoveBase::clearCostmapWindows(double size_x, double size_y){
  245. geometry_msgs::PoseStamped global_pose;
  246.  
  247. //clear the planner's costmap
  248. getRobotPose(global_pose, planner_costmap_ros_);
  249.  
  250. std::vector<geometry_msgs::Point> clear_poly;
  251. double x = global_pose.pose.position.x;
  252. double y = global_pose.pose.position.y;
  253. geometry_msgs::Point pt;
  254.  
  255. pt.x = x - size_x / ;
  256. pt.y = y - size_y / ;
  257. clear_poly.push_back(pt);
  258.  
  259. pt.x = x + size_x / ;
  260. pt.y = y - size_y / ;
  261. clear_poly.push_back(pt);
  262.  
  263. pt.x = x + size_x / ;
  264. pt.y = y + size_y / ;
  265. clear_poly.push_back(pt);
  266.  
  267. pt.x = x - size_x / ;
  268. pt.y = y + size_y / ;
  269. clear_poly.push_back(pt);
  270.  
  271. planner_costmap_ros_->getCostmap()->setConvexPolygonCost(clear_poly, costmap_2d::FREE_SPACE);
  272.  
  273. //clear the controller's costmap
  274. getRobotPose(global_pose, controller_costmap_ros_);
  275.  
  276. clear_poly.clear();
  277. x = global_pose.pose.position.x;
  278. y = global_pose.pose.position.y;
  279.  
  280. pt.x = x - size_x / ;
  281. pt.y = y - size_y / ;
  282. clear_poly.push_back(pt);
  283.  
  284. pt.x = x + size_x / ;
  285. pt.y = y - size_y / ;
  286. clear_poly.push_back(pt);
  287.  
  288. pt.x = x + size_x / ;
  289. pt.y = y + size_y / ;
  290. clear_poly.push_back(pt);
  291.  
  292. pt.x = x - size_x / ;
  293. pt.y = y + size_y / ;
  294. clear_poly.push_back(pt);
  295.  
  296. controller_costmap_ros_->getCostmap()->setConvexPolygonCost(clear_poly, costmap_2d::FREE_SPACE);
  297. }
  298.  
  299. bool MoveBase::clearCostmapsService(std_srvs::Empty::Request &req, std_srvs::Empty::Response &resp){
  300. //clear the costmaps
  301. boost::unique_lock<costmap_2d::Costmap2D::mutex_t> lock_controller(*(controller_costmap_ros_->getCostmap()->getMutex()));
  302. controller_costmap_ros_->resetLayers();
  303.  
  304. boost::unique_lock<costmap_2d::Costmap2D::mutex_t> lock_planner(*(planner_costmap_ros_->getCostmap()->getMutex()));
  305. planner_costmap_ros_->resetLayers();
  306. return true;
  307. }
  308.  
  309. bool MoveBase::planService(nav_msgs::GetPlan::Request &req, nav_msgs::GetPlan::Response &resp){
  310. if(as_->isActive()){
  311. ROS_ERROR("move_base must be in an inactive state to make a plan for an external user");
  312. return false;
  313. }
  314. //make sure we have a costmap for our planner
  315. if(planner_costmap_ros_ == NULL){
  316. ROS_ERROR("move_base cannot make a plan for you because it doesn't have a costmap");
  317. return false;
  318. }
  319.  
  320. //1. 获取起始点
  321. geometry_msgs::PoseStamped start;
  322. //如果起始点为空,设置global_pose为起始点
  323. if(req.start.header.frame_id.empty())
  324. {
  325. geometry_msgs::PoseStamped global_pose;
  326. if(!getRobotPose(global_pose, planner_costmap_ros_)){
  327. ROS_ERROR("move_base cannot make a plan for you because it could not get the start pose of the robot");
  328. return false;
  329. }
  330. start = global_pose;
  331. }
  332. else
  333. {
  334. start = req.start;
  335. }
  336.  
  337. //update the copy of the costmap the planner uses
  338. clearCostmapWindows( * clearing_radius_, * clearing_radius_);
  339.  
  340. //制定规划策略
  341. std::vector<geometry_msgs::PoseStamped> global_plan;
  342. if(!planner_->makePlan(start, req.goal, global_plan) || global_plan.empty()){
  343. ROS_DEBUG_NAMED("move_base","Failed to find a plan to exact goal of (%.2f, %.2f), searching for a feasible goal within tolerance",
  344. req.goal.pose.position.x, req.goal.pose.position.y);
  345.  
  346. //search outwards for a feasible goal within the specified tolerance在规定的公差范围内向外寻找可行的goal
  347. geometry_msgs::PoseStamped p;
  348. p = req.goal;
  349. bool found_legal = false;
  350. float resolution = planner_costmap_ros_->getCostmap()->getResolution();
  351. float search_increment = resolution*3.0;//以3倍分辨率的增量向外寻找
  352. if(req.tolerance > 0.0 && req.tolerance < search_increment) search_increment = req.tolerance;
  353. for(float max_offset = search_increment; max_offset <= req.tolerance && !found_legal; max_offset += search_increment) {
  354. for(float y_offset = ; y_offset <= max_offset && !found_legal; y_offset += search_increment) {
  355. for(float x_offset = ; x_offset <= max_offset && !found_legal; x_offset += search_increment) {
  356.  
  357. //不在本位置的外侧layer查找,太近的不找
  358. if(x_offset < max_offset-1e- && y_offset < max_offset-1e-) continue;
  359.  
  360. //从两个方向x、y查找精确的goal
  361. for(float y_mult = -1.0; y_mult <= 1.0 + 1e- && !found_legal; y_mult += 2.0) {
  362.  
  363. //第一次遍历如果偏移量过小,则去除这个点或者上一点
  364. if(y_offset < 1e- && y_mult < -1.0 + 1e-) continue;
  365.  
  366. for(float x_mult = -1.0; x_mult <= 1.0 + 1e- && !found_legal; x_mult += 2.0) {
  367. if(x_offset < 1e- && x_mult < -1.0 + 1e-) continue;
  368.  
  369. p.pose.position.y = req.goal.pose.position.y + y_offset * y_mult;
  370. p.pose.position.x = req.goal.pose.position.x + x_offset * x_mult;
  371.  
  372. if(planner_->makePlan(start, p, global_plan)){
  373. if(!global_plan.empty()){
  374.  
  375. //adding the (unreachable) original goal to the end of the global plan, in case the local planner can get you there
  376. //(the reachable goal should have been added by the global planner)
  377. global_plan.push_back(req.goal);
  378.  
  379. found_legal = true;
  380. ROS_DEBUG_NAMED("move_base", "Found a plan to point (%.2f, %.2f)", p.pose.position.x, p.pose.position.y);
  381. break;
  382. }
  383. }
  384. else{
  385. ROS_DEBUG_NAMED("move_base","Failed to find a plan to point (%.2f, %.2f)", p.pose.position.x, p.pose.position.y);
  386. }
  387. }
  388. }
  389. }
  390. }
  391. }
  392. }
  393.  
  394. //copy the plan into a message to send out
  395. resp.plan.poses.resize(global_plan.size());
  396. for(unsigned int i = ; i < global_plan.size(); ++i){
  397. resp.plan.poses[i] = global_plan[i];
  398. }
  399.  
  400. return true;
  401. }
  402. //析构函数
  403. MoveBase::~MoveBase(){
  404. recovery_behaviors_.clear();
  405.  
  406. delete dsrv_;
  407.  
  408. if(as_ != NULL)
  409. delete as_;
  410.  
  411. if(planner_costmap_ros_ != NULL)
  412. delete planner_costmap_ros_;
  413.  
  414. if(controller_costmap_ros_ != NULL)
  415. delete controller_costmap_ros_;
  416.  
  417. planner_thread_->interrupt();
  418. planner_thread_->join();
  419.  
  420. delete planner_thread_;
  421.  
  422. delete planner_plan_;
  423. delete latest_plan_;
  424. delete controller_plan_;
  425.  
  426. planner_.reset();
  427. tc_.reset();
  428. }
  429.  
  430. bool MoveBase::makePlan(const geometry_msgs::PoseStamped& goal, std::vector<geometry_msgs::PoseStamped>& plan){
  431. boost::unique_lock<costmap_2d::Costmap2D::mutex_t> lock(*(planner_costmap_ros_->getCostmap()->getMutex()));
  432.  
  433. //规划初始化
  434. plan.clear();
  435.  
  436. //激活句柄时调用
  437. if(planner_costmap_ros_ == NULL) {
  438. ROS_ERROR("Planner costmap ROS is NULL, unable to create global plan");
  439. return false;
  440. }
  441.  
  442. //得到机器人起始点
  443. geometry_msgs::PoseStamped global_pose;
  444. if(!getRobotPose(global_pose, planner_costmap_ros_)) {
  445. ROS_WARN("Unable to get starting pose of robot, unable to create global plan");
  446. return false;
  447. }
  448.  
  449. const geometry_msgs::PoseStamped& start = global_pose;
  450.  
  451. //如果规划失败或者返回一个长度为0的规划,则规划失败
  452. if(!planner_->makePlan(start, goal, plan) || plan.empty()){
  453. ROS_DEBUG_NAMED("move_base","Failed to find a plan to point (%.2f, %.2f)", goal.pose.position.x, goal.pose.position.y);
  454. return false;
  455. }
  456.  
  457. return true;
  458. }
  459.  
  460. void MoveBase::publishZeroVelocity(){
  461. geometry_msgs::Twist cmd_vel;
  462. cmd_vel.linear.x = 0.0;
  463. cmd_vel.linear.y = 0.0;
  464. cmd_vel.angular.z = 0.0;
  465. vel_pub_.publish(cmd_vel);
  466. }
  467.  
  468. bool MoveBase::isQuaternionValid(const geometry_msgs::Quaternion& q){
  469. //1、首先检查四元数是否元素完整
  470. if(!std::isfinite(q.x) || !std::isfinite(q.y) || !std::isfinite(q.z) || !std::isfinite(q.w)){
  471. ROS_ERROR("Quaternion has nans or infs... discarding as a navigation goal");
  472. return false;
  473. }
  474.  
  475. tf2::Quaternion tf_q(q.x, q.y, q.z, q.w);
  476.  
  477. //2、检查四元数是否趋近于0
  478. if(tf_q.length2() < 1e-){
  479. ROS_ERROR("Quaternion has length close to zero... discarding as navigation goal");
  480. return false;
  481. }
  482.  
  483. //3、对四元数规范化,转化为vector
  484. tf_q.normalize();
  485.  
  486. tf2::Vector3 up(, , );
  487.  
  488. double dot = up.dot(up.rotate(tf_q.getAxis(), tf_q.getAngle()));
  489.  
  490. if(fabs(dot - ) > 1e-){
  491. ROS_ERROR("Quaternion is invalid... for navigation the z-axis of the quaternion must be close to vertical.");
  492. return false;
  493. }
  494.  
  495. return true;
  496. }
  497.  
  498. geometry_msgs::PoseStamped MoveBase::goalToGlobalFrame(const geometry_msgs::PoseStamped& goal_pose_msg){
  499. std::string global_frame = planner_costmap_ros_->getGlobalFrameID();
  500. geometry_msgs::PoseStamped goal_pose, global_pose;
  501. goal_pose = goal_pose_msg;
  502.  
  503. //tf一下
  504. goal_pose.header.stamp = ros::Time();
  505.  
  506. try{
  507. tf_.transform(goal_pose_msg, global_pose, global_frame);
  508. }
  509. catch(tf2::TransformException& ex){
  510. ROS_WARN("Failed to transform the goal pose from %s into the %s frame: %s",
  511. goal_pose.header.frame_id.c_str(), global_frame.c_str(), ex.what());
  512. return goal_pose_msg;
  513. }
  514.  
  515. return global_pose;
  516. }
  517.  
  518. void MoveBase::wakePlanner(const ros::TimerEvent& event)
  519. {
  520. // we have slept long enough for rate
  521. planner_cond_.notify_one();
  522. }
  523.  
  524. //planner线程的入口。这个函数需要等待actionlib服务器的cbMoveBase::executeCb来唤醒启动。
  525. //主要作用是调用全局路径规划获取路径,同时保证规划的周期性以及规划超时清除goal
  526. void MoveBase::planThread(){
  527. ROS_DEBUG_NAMED("move_base_plan_thread","Starting planner thread...");
  528. ros::NodeHandle n;
  529. ros::Timer timer;
  530. bool wait_for_wake = false;
  531. //1. 创建递归锁
  532. boost::unique_lock<boost::recursive_mutex> lock(planner_mutex_);
  533. while(n.ok()){
  534. //check if we should run the planner (the mutex is locked)
  535. //2.判断是否阻塞线程
  536. while(wait_for_wake || !runPlanner_){
  537. //if we should not be running the planner then suspend this thread
  538. ROS_DEBUG_NAMED("move_base_plan_thread","Planner thread is suspending");
  539. //当 std::condition_variable 对象的某个 wait 函数被调用的时候,
  540. //它使用 std::unique_lock(通过 std::mutex) 来锁住当前线程。
  541. //当前线程会一直被阻塞,直到另外一个线程在相同的 std::condition_variable 对象上调用了 notification 函数来唤醒当前线程。
  542. planner_cond_.wait(lock);
  543. wait_for_wake = false;
  544. }
  545. ros::Time start_time = ros::Time::now();
  546.  
  547. //time to plan! get a copy of the goal and unlock the mutex
  548. geometry_msgs::PoseStamped temp_goal = planner_goal_;
  549. lock.unlock();
  550. ROS_DEBUG_NAMED("move_base_plan_thread","Planning...");
  551.  
  552. //run planner
  553.  
  554. //3. 获取规划的全局路径
  555. //这里的makePlan作用是获取机器人的位姿作为起点,然后调用全局规划器的makePlan返回规划路径,存储在planner_plan_
  556. planner_plan_->clear();
  557. bool gotPlan = n.ok() && makePlan(temp_goal, *planner_plan_);
  558.  
  559. //4.如果获得了plan,则将其赋值给latest_plan_
  560. if(gotPlan){
  561. ROS_DEBUG_NAMED("move_base_plan_thread","Got Plan with %zu points!", planner_plan_->size());
  562. //pointer swap the plans under mutex (the controller will pull from latest_plan_)
  563. std::vector<geometry_msgs::PoseStamped>* temp_plan = planner_plan_;
  564.  
  565. lock.lock();
  566. planner_plan_ = latest_plan_;
  567. latest_plan_ = temp_plan;
  568. last_valid_plan_ = ros::Time::now();
  569. planning_retries_ = ;
  570. new_global_plan_ = true;
  571.  
  572. ROS_DEBUG_NAMED("move_base_plan_thread","Generated a plan from the base_global_planner");
  573.  
  574. //make sure we only start the controller if we still haven't reached the goal
  575. if(runPlanner_)
  576. state_ = CONTROLLING;
  577. if(planner_frequency_ <= )
  578. runPlanner_ = false;
  579. lock.unlock();
  580. }
  581.  
  582. //5. 达到一定条件后停止路径规划,进入清障模式
  583. //如果没有规划出路径,并且处于PLANNING状态,则判断是否超过最大规划周期或者规划次数
  584. //如果是则进入自转模式,否则应该会等待MoveBase::executeCycle的唤醒再次规划
  585. else if(state_==PLANNING){
  586. //仅在MoveBase::executeCb及其调用的MoveBase::executeCycle或者重置状态时会被设置为PLANNING
  587. //一般是刚获得新目标,或者得到路径但计算不出下一步控制时重新进行路径规划
  588. ROS_DEBUG_NAMED("move_base_plan_thread","No Plan...");
  589. ros::Time attempt_end = last_valid_plan_ + ros::Duration(planner_patience_);
  590.  
  591. //check if we've tried to make a plan for over our time limit or our maximum number of retries
  592. //issue #496: we stop planning when one of the conditions is true, but if max_planning_retries_
  593. //is negative (the default), it is just ignored and we have the same behavior as ever
  594. lock.lock();
  595. planning_retries_++;
  596. if(runPlanner_ &&
  597. (ros::Time::now() > attempt_end || planning_retries_ > uint32_t(max_planning_retries_))){
  598. //we'll move into our obstacle clearing mode
  599. state_ = CLEARING;
  600. runPlanner_ = false; // proper solution for issue #523
  601. publishZeroVelocity();
  602. recovery_trigger_ = PLANNING_R;
  603. }
  604.  
  605. lock.unlock();
  606. }
  607.  
  608. //take the mutex for the next iteration
  609. lock.lock();
  610.  
  611. //6.设置睡眠模式
  612. //如果还没到规划周期则定时器睡眠,在定时器中断中通过planner_cond_唤醒,这里规划周期为0
  613. if(planner_frequency_ > ){
  614. ros::Duration sleep_time = (start_time + ros::Duration(1.0/planner_frequency_)) - ros::Time::now();
  615. if (sleep_time > ros::Duration(0.0)){
  616. wait_for_wake = true;
  617. timer = n.createTimer(sleep_time, &MoveBase::wakePlanner, this);
  618. }
  619. }
  620. }
  621. }
  622.  
  623. void MoveBase::executeCb(const move_base_msgs::MoveBaseGoalConstPtr& move_base_goal)
  624. {
  625.  
  626. //1. 如果目标非法,返回
  627. if(!isQuaternionValid(move_base_goal->target_pose.pose.orientation)){
  628. as_->setAborted(move_base_msgs::MoveBaseResult(), "Aborting on goal because it was sent with an invalid quaternion");
  629. return;
  630. }
  631.  
  632. //2. 将目标的坐标系统一转换为全局坐标系
  633. geometry_msgs::PoseStamped goal = goalToGlobalFrame(move_base_goal->target_pose);
  634.  
  635. //3. 设置目标点并唤醒路径规划线程
  636. boost::unique_lock<boost::recursive_mutex> lock(planner_mutex_);
  637. planner_goal_ = goal;
  638. runPlanner_ = true;
  639. planner_cond_.notify_one();
  640. lock.unlock();
  641.  
  642. current_goal_pub_.publish(goal);
  643. std::vector<geometry_msgs::PoseStamped> global_plan;
  644.  
  645. ros::Rate r(controller_frequency_);
  646. //4. 开启costmap更新
  647. if(shutdown_costmaps_){
  648. ROS_DEBUG_NAMED("move_base","Starting up costmaps that were shut down previously");
  649. planner_costmap_ros_->start();
  650. controller_costmap_ros_->start();
  651. }
  652.  
  653. //5. 重置时间标志位
  654. last_valid_control_ = ros::Time::now();
  655. last_valid_plan_ = ros::Time::now();
  656. last_oscillation_reset_ = ros::Time::now();
  657. planning_retries_ = ;
  658.  
  659. ros::NodeHandle n;
  660.  
  661. //6. 开启循环,循环判断是否有新的goal抢占
  662. while(n.ok())
  663. {
  664.  
  665. //7. 修改循环频率
  666. if(c_freq_change_)
  667. {
  668. ROS_INFO("Setting controller frequency to %.2f", controller_frequency_);
  669. r = ros::Rate(controller_frequency_);
  670. c_freq_change_ = false;
  671. }
  672.  
  673. //8. 如果获得一个抢占式目标
  674. if(as_->isPreemptRequested()){
  675. if(as_->isNewGoalAvailable()){
  676. //if we're active and a new goal is available, we'll accept it, but we won't shut anything down
  677. move_base_msgs::MoveBaseGoal new_goal = *as_->acceptNewGoal();
  678.  
  679. //9.如果目标无效,则返回
  680. if(!isQuaternionValid(new_goal.target_pose.pose.orientation)){
  681. as_->setAborted(move_base_msgs::MoveBaseResult(), "Aborting on goal because it was sent with an invalid quaternion");
  682. return;
  683. }
  684. //10.将目标转换为全局坐标系
  685. goal = goalToGlobalFrame(new_goal.target_pose);
  686.  
  687. //we'll make sure that we reset our state for the next execution cycle
  688.  
  689. //11.设置状态为PLANNING
  690. recovery_index_ = ;
  691. state_ = PLANNING;
  692.  
  693. //we have a new goal so make sure the planner is awake
  694.  
  695. //12. 设置目标点并唤醒路径规划线程
  696. lock.lock();
  697. planner_goal_ = goal;
  698. runPlanner_ = true;
  699. planner_cond_.notify_one();
  700. lock.unlock();
  701.  
  702. //13. 把goal发布给可视化工具
  703. ROS_DEBUG_NAMED("move_base","move_base has received a goal of x: %.2f, y: %.2f", goal.pose.position.x, goal.pose.position.y);
  704. current_goal_pub_.publish(goal);
  705.  
  706. //make sure to reset our timeouts and counters
  707. //14. 重置规划时间
  708. last_valid_control_ = ros::Time::now();
  709. last_valid_plan_ = ros::Time::now();
  710. last_oscillation_reset_ = ros::Time::now();
  711. planning_retries_ = ;
  712. }
  713. else {
  714.  
  715. //14.重置状态,设置为抢占式任务
  716. //if we've been preempted explicitly we need to shut things down
  717. resetState();
  718.  
  719. //通知ActionServer已成功抢占
  720. ROS_DEBUG_NAMED("move_base","Move base preempting the current goal");
  721. as_->setPreempted();
  722.  
  723. //we'll actually return from execute after preempting
  724. return;
  725. }
  726. }
  727.  
  728. //we also want to check if we've changed global frames because we need to transform our goal pose
  729. //15.如果目标点的坐标系和全局地图的坐标系不相同
  730. if(goal.header.frame_id != planner_costmap_ros_->getGlobalFrameID()){
  731. //16,转换目标点坐标系
  732. goal = goalToGlobalFrame(goal);
  733.  
  734. //we want to go back to the planning state for the next execution cycle
  735. recovery_index_ = ;
  736. state_ = PLANNING;
  737.  
  738. //17. 设置目标点并唤醒路径规划线程
  739. lock.lock();
  740. planner_goal_ = goal;
  741. runPlanner_ = true;
  742. planner_cond_.notify_one();
  743. lock.unlock();
  744.  
  745. //publish the goal point to the visualizer
  746. ROS_DEBUG_NAMED("move_base","The global frame for move_base has changed, new frame: %s, new goal position x: %.2f, y: %.2f", goal.header.frame_id.c_str(), goal.pose.position.x, goal.pose.position.y);
  747. current_goal_pub_.publish(goal);
  748.  
  749. //18.重置规划器相关时间标志位
  750. last_valid_control_ = ros::Time::now();
  751. last_valid_plan_ = ros::Time::now();
  752. last_oscillation_reset_ = ros::Time::now();
  753. planning_retries_ = ;
  754. }
  755.  
  756. //for timing that gives real time even in simulation
  757. ros::WallTime start = ros::WallTime::now();
  758.  
  759. //19. 到达目标点的真正工作,控制机器人进行跟随
  760. bool done = executeCycle(goal, global_plan);
  761.  
  762. //20.如果完成任务则返回
  763. if(done)
  764. return;
  765.  
  766. //check if execution of the goal has completed in some way
  767.  
  768. ros::WallDuration t_diff = ros::WallTime::now() - start;
  769. ROS_DEBUG_NAMED("move_base","Full control cycle time: %.9f\n", t_diff.toSec());
  770. //21. 执行休眠动作
  771. r.sleep();
  772. //make sure to sleep for the remainder of our cycle time
  773. if(r.cycleTime() > ros::Duration( / controller_frequency_) && state_ == CONTROLLING)
  774. ROS_WARN("Control loop missed its desired rate of %.4fHz... the loop actually took %.4f seconds", controller_frequency_, r.cycleTime().toSec());
  775. }
  776.  
  777. //22. 唤醒计划线程,以便它可以干净地退出
  778. lock.lock();
  779. runPlanner_ = true;
  780. planner_cond_.notify_one();
  781. lock.unlock();
  782.  
  783. //23. 如果节点结束就终止并返回
  784. as_->setAborted(move_base_msgs::MoveBaseResult(), "Aborting on the goal because the node has been killed");
  785. return;
  786. }
  787.  
  788. double MoveBase::distance(const geometry_msgs::PoseStamped& p1, const geometry_msgs::PoseStamped& p2)
  789. {
  790. return hypot(p1.pose.position.x - p2.pose.position.x, p1.pose.position.y - p2.pose.position.y);
  791. }
  792.  
  793. //两个参数分别是目标点位姿以及规划出的全局路径.通过这两个参数,实现以下功能:
  794. //利用局部路径规划器直接输出轮子速度,控制机器人按照路径走到目标点,成功返回真,否则返回假。在actionlib server的回调MoveBase::executeCb中被调用。
  795. bool MoveBase::executeCycle(geometry_msgs::PoseStamped& goal, std::vector<geometry_msgs::PoseStamped>& global_plan){
  796.  
  797. boost::recursive_mutex::scoped_lock ecl(configuration_mutex_);
  798. //we need to be able to publish velocity commands
  799. geometry_msgs::Twist cmd_vel;
  800.  
  801. //1.获取机器人当前位置
  802. geometry_msgs::PoseStamped global_pose;
  803. getRobotPose(global_pose, planner_costmap_ros_);
  804. const geometry_msgs::PoseStamped& current_position = global_pose;
  805.  
  806. //push the feedback out
  807. move_base_msgs::MoveBaseFeedback feedback;
  808. feedback.base_position = current_position;
  809. as_->publishFeedback(feedback);
  810.  
  811. //2.重置震荡标志位
  812. if(distance(current_position, oscillation_pose_) >= oscillation_distance_)
  813. {
  814. last_oscillation_reset_ = ros::Time::now();
  815. oscillation_pose_ = current_position;
  816.  
  817. //if our last recovery was caused by oscillation, we want to reset the recovery index
  818. if(recovery_trigger_ == OSCILLATION_R)
  819. recovery_index_ = ;
  820. }
  821.  
  822. //3.地图数据超时,即观测传感器数据不够新,停止机器人,返回false
  823. if(!controller_costmap_ros_->isCurrent()){
  824. ROS_WARN("[%s]:Sensor data is out of date, we're not going to allow commanding of the base for safety",ros::this_node::getName().c_str());
  825. publishZeroVelocity();
  826. return false;
  827. }
  828.  
  829. //4. 如果获取新的全局路径,则将它传输给控制器,完成latest_plan_到controller_plan_的转换
  830. if(new_global_plan_){
  831. //make sure to set the new plan flag to false
  832. new_global_plan_ = false;
  833.  
  834. ROS_DEBUG_NAMED("move_base","Got a new plan...swap pointers");
  835.  
  836. //do a pointer swap under mutex
  837. std::vector<geometry_msgs::PoseStamped>* temp_plan = controller_plan_;
  838.  
  839. boost::unique_lock<boost::recursive_mutex> lock(planner_mutex_);
  840. controller_plan_ = latest_plan_;
  841. latest_plan_ = temp_plan;
  842. lock.unlock();
  843. ROS_DEBUG_NAMED("move_base","pointers swapped!");
  844.  
  845. //5. 给控制器设置全局路径
  846. if(!tc_->setPlan(*controller_plan_)){
  847. //ABORT and SHUTDOWN COSTMAPS
  848. ROS_ERROR("Failed to pass global plan to the controller, aborting.");
  849. resetState();
  850.  
  851. //disable the planner thread
  852. lock.lock();
  853. runPlanner_ = false;
  854. lock.unlock();
  855. //6.设置动作中断,返回true
  856. as_->setAborted(move_base_msgs::MoveBaseResult(), "Failed to pass global plan to the controller.");
  857. return true;
  858. }
  859.  
  860. //如果全局路径有效,则不需要recovery
  861. if(recovery_trigger_ == PLANNING_R)
  862. recovery_index_ = ;
  863. }
  864.  
  865. //5. move_base 状态机,处理导航的控制逻辑
  866. //一般默认状态或者接收到一个有效goal时是PLANNING,在规划出全局路径后state_会由PLANNING->CONTROLLING
  867. //如果规划失败则由PLANNING->CLEARING。
  868. switch(state_){
  869. //6. 机器人规划状态,尝试获取一条全局路径
  870. case PLANNING:
  871. {
  872. boost::recursive_mutex::scoped_lock lock(planner_mutex_);
  873. runPlanner_ = true;
  874. planner_cond_.notify_one();//还在PLANNING中则唤醒规划线程让它干活
  875. }
  876. ROS_DEBUG_NAMED("move_base","Waiting for plan, in the planning state.");
  877. break;
  878.  
  879. //7.机器人控制状态,尝试获取一个有效的速度命令
  880. case CONTROLLING:
  881. ROS_DEBUG_NAMED("move_base","In controlling state.");
  882.  
  883. //8.如果到达目标点,重置状态,设置动作成功,返回true
  884. if(tc_->isGoalReached()){
  885. ROS_DEBUG_NAMED("move_base","Goal reached!");
  886. resetState();
  887.  
  888. //disable the planner thread
  889. boost::unique_lock<boost::recursive_mutex> lock(planner_mutex_);
  890. runPlanner_ = false;
  891. lock.unlock();
  892.  
  893. as_->setSucceeded(move_base_msgs::MoveBaseResult(), "Goal reached.");
  894. return true;
  895. }
  896.  
  897. //9. 如果超过震荡时间,停止机器人,设置清障标志位
  898. if(oscillation_timeout_ > 0.0 &&
  899. last_oscillation_reset_ + ros::Duration(oscillation_timeout_) < ros::Time::now())
  900. {
  901. publishZeroVelocity();
  902. state_ = CLEARING;
  903. recovery_trigger_ = OSCILLATION_R;
  904. }
  905.  
  906. {
  907. boost::unique_lock<costmap_2d::Costmap2D::mutex_t> lock(*(controller_costmap_ros_->getCostmap()->getMutex()));
  908. //10. 获取有效速度,如果获取成功,直接发布到cmd_vel
  909. if(tc_->computeVelocityCommands(cmd_vel)){
  910. ROS_DEBUG_NAMED( "move_base", "Got a valid command from the local planner: %.3lf, %.3lf, %.3lf",
  911. cmd_vel.linear.x, cmd_vel.linear.y, cmd_vel.angular.z );
  912. last_valid_control_ = ros::Time::now();
  913. //make sure that we send the velocity command to the base
  914. vel_pub_.publish(cmd_vel);
  915. if(recovery_trigger_ == CONTROLLING_R)
  916. recovery_index_ = ;
  917. }
  918. else {
  919. //11.如果没有获取到有效速度
  920. ROS_DEBUG_NAMED("move_base", "The local planner could not find a valid plan.");
  921. ros::Time attempt_end = last_valid_control_ + ros::Duration(controller_patience_);
  922.  
  923. //12.判断超过尝试时间,如果超时,停止机器人,进入清障模式
  924. if(ros::Time::now() > attempt_end){
  925. //we'll move into our obstacle clearing mode
  926. publishZeroVelocity();
  927. state_ = CLEARING;
  928. recovery_trigger_ = CONTROLLING_R;
  929. }
  930. else{
  931. //如果不超时,让全局再规划一个路径
  932. last_valid_plan_ = ros::Time::now();
  933. planning_retries_ = ;
  934. state_ = PLANNING;
  935. publishZeroVelocity();
  936.  
  937. //enable the planner thread in case it isn't running on a clock
  938. boost::unique_lock<boost::recursive_mutex> lock(planner_mutex_);
  939. runPlanner_ = true;
  940. planner_cond_.notify_one();
  941. lock.unlock();
  942. }
  943. }
  944. }
  945.  
  946. break;
  947.  
  948. //13. 规划或者控制失败,恢复或者进入到清障模式
  949. case CLEARING:
  950. ROS_DEBUG_NAMED("move_base","In clearing/recovery state");
  951.  
  952. //14. 有可用恢复器,执行恢复动作,设置状态为PLANNING
  953. if(recovery_behavior_enabled_ && recovery_index_ < recovery_behaviors_.size()){
  954. ROS_DEBUG_NAMED("move_base_recovery","Executing behavior %u of %zu", recovery_index_, recovery_behaviors_.size());
  955. recovery_behaviors_[recovery_index_]->runBehavior();
  956.  
  957. //we at least want to give the robot some time to stop oscillating after executing the behavior
  958. last_oscillation_reset_ = ros::Time::now();
  959.  
  960. //we'll check if the recovery behavior actually worked
  961. ROS_DEBUG_NAMED("move_base_recovery","Going back to planning state");
  962. last_valid_plan_ = ros::Time::now();
  963. planning_retries_ = ;
  964. state_ = PLANNING;
  965.  
  966. //update the index of the next recovery behavior that we'll try
  967. recovery_index_++;
  968. }
  969. else{
  970.  
  971. //15.没有可用恢复器,结束动作,返回true
  972. ROS_DEBUG_NAMED("move_base_recovery","All recovery behaviors have failed, locking the planner and disabling it.");
  973. //disable the planner thread
  974. boost::unique_lock<boost::recursive_mutex> lock(planner_mutex_);
  975. runPlanner_ = false;
  976. lock.unlock();
  977.  
  978. ROS_DEBUG_NAMED("move_base_recovery","Something should abort after this.");
  979.  
  980. if(recovery_trigger_ == CONTROLLING_R){
  981. ROS_ERROR("Aborting because a valid control could not be found. Even after executing all recovery behaviors");
  982. as_->setAborted(move_base_msgs::MoveBaseResult(), "Failed to find a valid control. Even after executing recovery behaviors.");
  983. }
  984. else if(recovery_trigger_ == PLANNING_R){
  985. ROS_ERROR("Aborting because a valid plan could not be found. Even after executing all recovery behaviors");
  986. as_->setAborted(move_base_msgs::MoveBaseResult(), "Failed to find a valid plan. Even after executing recovery behaviors.");
  987. }
  988. else if(recovery_trigger_ == OSCILLATION_R){
  989. ROS_ERROR("Aborting because the robot appears to be oscillating over and over. Even after executing all recovery behaviors");
  990. as_->setAborted(move_base_msgs::MoveBaseResult(), "Robot is oscillating. Even after executing recovery behaviors.");
  991. }
  992. resetState();
  993. return true;
  994. }
  995. break;
  996. default:
  997. ROS_ERROR("This case should never be reached, something is wrong, aborting");
  998. resetState();
  999. //disable the planner thread
  1000. boost::unique_lock<boost::recursive_mutex> lock(planner_mutex_);
  1001. runPlanner_ = false;
  1002. lock.unlock();
  1003. as_->setAborted(move_base_msgs::MoveBaseResult(), "Reached a case that should not be hit in move_base. This is a bug, please report it.");
  1004. return true;
  1005. }
  1006.  
  1007. //we aren't done yet
  1008. return false;
  1009. }
  1010.  
  1011. //recovery是指恢复的规划器,其跟全局规划器和局部规划器是同一个等级的。
  1012. //不同的是,它是在机器人在局部代价地图或者全局代价地图中找不到路时才会被调用,比如rotate_recovery让机器人原地360°旋转,clear_costmap_recovery将代价地图恢复到静态地图的样子。
  1013. bool MoveBase::loadRecoveryBehaviors(ros::NodeHandle node){
  1014. XmlRpc::XmlRpcValue behavior_list;
  1015. if(node.getParam("recovery_behaviors", behavior_list)){
  1016. if(behavior_list.getType() == XmlRpc::XmlRpcValue::TypeArray){
  1017. for(int i = ; i < behavior_list.size(); ++i){
  1018. if(behavior_list[i].getType() == XmlRpc::XmlRpcValue::TypeStruct){
  1019. if(behavior_list[i].hasMember("name") && behavior_list[i].hasMember("type")){
  1020. //check for recovery behaviors with the same name
  1021. for(int j = i + ; j < behavior_list.size(); j++){
  1022. if(behavior_list[j].getType() == XmlRpc::XmlRpcValue::TypeStruct){
  1023. if(behavior_list[j].hasMember("name") && behavior_list[j].hasMember("type")){
  1024. std::string name_i = behavior_list[i]["name"];
  1025. std::string name_j = behavior_list[j]["name"];
  1026. if(name_i == name_j){
  1027. ROS_ERROR("A recovery behavior with the name %s already exists, this is not allowed. Using the default recovery behaviors instead.",
  1028. name_i.c_str());
  1029. return false;
  1030. }
  1031. }
  1032. }
  1033. }
  1034. }
  1035. else{
  1036. ROS_ERROR("Recovery behaviors must have a name and a type and this does not. Using the default recovery behaviors instead.");
  1037. return false;
  1038. }
  1039. }
  1040. else{
  1041. ROS_ERROR("Recovery behaviors must be specified as maps, but they are XmlRpcType %d. We'll use the default recovery behaviors instead.",
  1042. behavior_list[i].getType());
  1043. return false;
  1044. }
  1045. }
  1046.  
  1047. //if we've made it to this point, we know that the list is legal so we'll create all the recovery behaviors
  1048. for(int i = ; i < behavior_list.size(); ++i){
  1049. try{
  1050. //check if a non fully qualified name has potentially been passed in
  1051. if(!recovery_loader_.isClassAvailable(behavior_list[i]["type"])){
  1052. std::vector<std::string> classes = recovery_loader_.getDeclaredClasses();
  1053. for(unsigned int i = ; i < classes.size(); ++i){
  1054. if(behavior_list[i]["type"] == recovery_loader_.getName(classes[i])){
  1055. //if we've found a match... we'll get the fully qualified name and break out of the loop
  1056. ROS_WARN("Recovery behavior specifications should now include the package name. You are using a deprecated API. Please switch from %s to %s in your yaml file.",
  1057. std::string(behavior_list[i]["type"]).c_str(), classes[i].c_str());
  1058. behavior_list[i]["type"] = classes[i];
  1059. break;
  1060. }
  1061. }
  1062. }
  1063.  
  1064. boost::shared_ptr<nav_core::RecoveryBehavior> behavior(recovery_loader_.createInstance(behavior_list[i]["type"]));
  1065.  
  1066. //shouldn't be possible, but it won't hurt to check
  1067. if(behavior.get() == NULL){
  1068. ROS_ERROR("The ClassLoader returned a null pointer without throwing an exception. This should not happen");
  1069. return false;
  1070. }
  1071.  
  1072. //initialize the recovery behavior with its name
  1073. behavior->initialize(behavior_list[i]["name"], &tf_, planner_costmap_ros_, controller_costmap_ros_);
  1074. recovery_behaviors_.push_back(behavior);
  1075. }
  1076. catch(pluginlib::PluginlibException& ex){
  1077. ROS_ERROR("Failed to load a plugin. Using default recovery behaviors. Error: %s", ex.what());
  1078. return false;
  1079. }
  1080. }
  1081. }
  1082. else{
  1083. ROS_ERROR("The recovery behavior specification must be a list, but is of XmlRpcType %d. We'll use the default recovery behaviors instead.",
  1084. behavior_list.getType());
  1085. return false;
  1086. }
  1087. }
  1088. else{
  1089. //if no recovery_behaviors are specified, we'll just load the defaults
  1090. return false;
  1091. }
  1092.  
  1093. //if we've made it here... we've constructed a recovery behavior list successfully
  1094. return true;
  1095. }
  1096.  
  1097. //we'll load our default recovery behaviors here
  1098. void MoveBase::loadDefaultRecoveryBehaviors(){
  1099. recovery_behaviors_.clear();
  1100. try{
  1101. //we need to set some parameters based on what's been passed in to us to maintain backwards compatibility
  1102. ros::NodeHandle n("~");
  1103. n.setParam("conservative_reset/reset_distance", conservative_reset_dist_);
  1104. n.setParam("aggressive_reset/reset_distance", circumscribed_radius_ * );
  1105.  
  1106. //1、加载recovery behavior清理costmap
  1107. boost::shared_ptr<nav_core::RecoveryBehavior> cons_clear(recovery_loader_.createInstance("clear_costmap_recovery/ClearCostmapRecovery"));
  1108. cons_clear->initialize("conservative_reset", &tf_, planner_costmap_ros_, controller_costmap_ros_);
  1109. recovery_behaviors_.push_back(cons_clear);
  1110.  
  1111. //2、加载recovery behavior 原地旋转
  1112. boost::shared_ptr<nav_core::RecoveryBehavior> rotate(recovery_loader_.createInstance("rotate_recovery/RotateRecovery"));
  1113. if(clearing_rotation_allowed_){
  1114. rotate->initialize("rotate_recovery", &tf_, planner_costmap_ros_, controller_costmap_ros_);
  1115. recovery_behaviors_.push_back(rotate);
  1116. }
  1117.  
  1118. //3、加载 recovery behavior 重置 costmap
  1119. boost::shared_ptr<nav_core::RecoveryBehavior> ags_clear(recovery_loader_.createInstance("clear_costmap_recovery/ClearCostmapRecovery"));
  1120. ags_clear->initialize("aggressive_reset", &tf_, planner_costmap_ros_, controller_costmap_ros_);
  1121. recovery_behaviors_.push_back(ags_clear);
  1122.  
  1123. //4、再一次旋转
  1124. if(clearing_rotation_allowed_)
  1125. recovery_behaviors_.push_back(rotate);
  1126. }
  1127. catch(pluginlib::PluginlibException& ex){
  1128. ROS_FATAL("Failed to load a plugin. This should not happen on default recovery behaviors. Error: %s", ex.what());
  1129. }
  1130.  
  1131. return;
  1132. }
  1133.  
  1134. void MoveBase::resetState(){
  1135. // Disable the planner thread
  1136. boost::unique_lock<boost::recursive_mutex> lock(planner_mutex_);
  1137. runPlanner_ = false;
  1138. lock.unlock();
  1139.  
  1140. // Reset statemachine
  1141. state_ = PLANNING;
  1142. recovery_index_ = ;
  1143. recovery_trigger_ = PLANNING_R;
  1144. publishZeroVelocity();
  1145.  
  1146. //if we shutdown our costmaps when we're deactivated... we'll do that now
  1147. if(shutdown_costmaps_){
  1148. ROS_DEBUG_NAMED("move_base","Stopping costmaps");
  1149. planner_costmap_ros_->stop();
  1150. controller_costmap_ros_->stop();
  1151. }
  1152. }
  1153.  
  1154. bool MoveBase::getRobotPose(geometry_msgs::PoseStamped& global_pose, costmap_2d::Costmap2DROS* costmap)
  1155. {
  1156. tf2::toMsg(tf2::Transform::getIdentity(), global_pose.pose);
  1157. geometry_msgs::PoseStamped robot_pose;
  1158. tf2::toMsg(tf2::Transform::getIdentity(), robot_pose.pose);
  1159. robot_pose.header.frame_id = robot_base_frame_;
  1160. robot_pose.header.stamp = ros::Time(); // latest available
  1161. ros::Time current_time = ros::Time::now(); // save time for checking tf delay later
  1162.  
  1163. // 转换到统一的全局坐标
  1164. try
  1165. {
  1166. tf_.transform(robot_pose, global_pose, costmap->getGlobalFrameID());
  1167. }
  1168. catch (tf2::LookupException& ex)
  1169. {
  1170. ROS_ERROR_THROTTLE(1.0, "No Transform available Error looking up robot pose: %s\n", ex.what());
  1171. return false;
  1172. }
  1173. catch (tf2::ConnectivityException& ex)
  1174. {
  1175. ROS_ERROR_THROTTLE(1.0, "Connectivity Error looking up robot pose: %s\n", ex.what());
  1176. return false;
  1177. }
  1178. catch (tf2::ExtrapolationException& ex)
  1179. {
  1180. ROS_ERROR_THROTTLE(1.0, "Extrapolation Error looking up robot pose: %s\n", ex.what());
  1181. return false;
  1182. }
  1183.  
  1184. // 全局坐标时间戳是否在costmap要求下
  1185. if (current_time.toSec() - global_pose.header.stamp.toSec() > costmap->getTransformTolerance())
  1186. {
  1187. ROS_WARN_THROTTLE(1.0, "Transform timeout for %s. " \
  1188. "Current time: %.4f, pose stamp: %.4f, tolerance: %.4f", costmap->getName().c_str(),
  1189. current_time.toSec(), global_pose.header.stamp.toSec(), costmap->getTransformTolerance());
  1190. return false;
  1191. }
  1192.  
  1193. return true;
  1194. }
  1195. };

Navigation源码(一) move_base最全解析的更多相关文章

  1. TreeMap源码实现类中文全解析

    /** * 基于红黑树(Red-Black tree)的 NavigableMap 实现.该映射根据其键的自然顺序进行排序, * 或者根据创建映射时提供的Comparator 进行排序,具体取决于使用 ...

  2. UCanCode发布升级E-Form++可视化源码组件库2015全新版 (V23.01)!

    2015年4月. 成都 UCanCode发布升级E-Form++可视化源码组件库2015全新版 (V23.01)! --- 全面性能提升,UCanCode有史以来最强大的版本发布! E-Form++可 ...

  3. UCanCode发布升级E-Form++可视化源码组件库2014 全新版 (V20.01)!

    UCanCode发布升级E-Form++可视化源码组件库2014 全新版 (V20.01)! --- UCanCode有史以来最强大的版本发布! E-Form++可视化源码组件库企业版本2014最新版 ...

  4. Spring源码情操陶冶#task:scheduled-tasks解析器

    承接前文Spring源码情操陶冶#task:executor解析器,在前文基础上解析我们常用的spring中的定时任务的节点配置.备注:此文建立在spring的4.2.3.RELEASE版本 附例 S ...

  5. springMVC源码分析--HandlerMethodReturnValueHandlerComposite返回值解析器集合(二)

    在上一篇博客springMVC源码分析--HandlerMethodReturnValueHandler返回值解析器(一)我们介绍了返回值解析器HandlerMethodReturnValueHand ...

  6. UCanCode发布升级E-Form++可视化源码组件库2018全新版 !

    2018年. 成都 UCanCode发布升级E-Form++可视化源码组件库2018全新版 ! --- 全面性能提升,UCanCode有史以来最强大的版本发布! E-Form++可视化源码组件库企业版 ...

  7. 曹工说Spring Boot源码(8)-- Spring解析xml文件,到底从中得到了什么(util命名空间)

    写在前面的话 相关背景及资源: 曹工说Spring Boot源码(1)-- Bean Definition到底是什么,附spring思维导图分享 曹工说Spring Boot源码(2)-- Bean ...

  8. 曹工说Spring Boot源码(9)-- Spring解析xml文件,到底从中得到了什么(context命名空间上)

    写在前面的话 相关背景及资源: 曹工说Spring Boot源码(1)-- Bean Definition到底是什么,附spring思维导图分享 曹工说Spring Boot源码(2)-- Bean ...

  9. # 曹工说Spring Boot源码(10)-- Spring解析xml文件,到底从中得到了什么(context:annotation-config 解析)

    写在前面的话 相关背景及资源: 曹工说Spring Boot源码(1)-- Bean Definition到底是什么,附spring思维导图分享 曹工说Spring Boot源码(2)-- Bean ...

  10. 曹工说Spring Boot源码(12)-- Spring解析xml文件,到底从中得到了什么(context:component-scan完整解析)

    写在前面的话 相关背景及资源: 曹工说Spring Boot源码(1)-- Bean Definition到底是什么,附spring思维导图分享 曹工说Spring Boot源码(2)-- Bean ...

随机推荐

  1. ACM进阶之路

    第一阶段:练经典常用算法,下面的每个算法给我打上十到二十遍,同时自己精简代码, 因为太常用,所以要练到写时不用想,10-15分钟内打完,甚至关掉显示器都可以把程序打 出来. 3.大数(高精度)加减乘除 ...

  2. Git主库私库相关操作操作

    命令1: git remote add 库名称 库地址 说明:写好的代码提交到两个git远端,git remote add是将另一个库地址设置进来 命令2: git fetch 库名称 分支名称 说明 ...

  3. Educational Codeforces Round 81 (Rated for Div. 2) - D. Same GCDs(数学)

    题目链接:Same GCDs 题意:给你两个数$a$,$m(1 \leq a < m \leq 10^{10})$,求有多少个$x$满足:$0 \leq x < m$且$gcd(a,m)= ...

  4. cnpm - 解决 " cnpm : 无法加载文件 C:\Users\93457\AppData\Roaming\npm\cnpm.ps1,因为在此系统上禁止运行脚本。有关详细信息 。。。 "

    1.在win10 系统中搜索框 输入 Windos PowerShell选择 管理员身份运行 2,打开了powershell命令行之后,输入 set-ExecutionPolicy RemoteSig ...

  5. idea设置单行注释格式(包括配置文件)

    idea中文件单行注释默认在行首位置 修改方法:进入File-->Settings-->Editor-->Code Style-->Java,修改Code Generation ...

  6. Eclipse Tomcat 7.0 添加WEB项目报错:Tomcat version 7.0 only supports J2EE 1.2, 1.3, 1.4, and Java EE 5 and 6 Web modules

    前言 我叫梅乾花,我误闯了“从零开始的程序世界”,遭受到了前所未有的的困难,为了活下去,为了看见美好的明天,我开始学习之旅. 问题篇我打开了"Eclipse",将项目导入其中,开启 ...

  7. 201771010135杨蓉庆 《面对对象程序设计(java)》第九周学习总结

    第7章 异常.日志.断言和调试 1.实验目的与要求 (1) 掌握java异常处理技术: (2) 了解断言的用法: (3) 了解日志的用途: (4) 掌握程序基础调试技巧: 一.理论知识 1.异常:在程 ...

  8. Nexus-vPC和STP BPDU

    1.为了交互vPC拓扑,STP机制被修改适应到vPC peer环境.2.对于vPC ports,只有主角色运行STP,换句话说,vPC下的STP由主角色设备控制.3.只有主角色设备在DP(指定端口)上 ...

  9. java web第一次课堂测试1

    ---恢复内容开始--- 要求如图: 本程序包括四个文件,一个显示界面的jsp文件,一个dao层文件,一个servlet层文件 一个连接数据库的文件 下面依次附上代码: 前端界面: <%@ pa ...

  10. Kafka 消息的消费原理

    https://www.cnblogs.com/huxi2b/p/6061110.html 1.老版本的kafka的offset是维护在zk上的,新版本的kafka把consumer的offset维护 ...