当前位置:   article > 正文

Cartographer 3D建图与纯定位(在线建图、保存和纯定位)_cartographer定位

cartographer定位

1 Cartographer安装(Ubuntu8.04 melodic)

参考链接:

https://blog.csdn.net/YOULANSHENGMENG/article/details/125059416https://blog.csdn.net/YOULANSHENGMENG/article/details/125059416

1.1 安装依赖包

  1. sudo apt-get update
  2. sudo apt-get install -y google-mock libboost-all-dev  libeigen3-dev libgflags-dev libgoogle-glog-dev liblua5.2-dev libprotobuf-dev  libsuitesparse-dev libwebp-dev ninja-build protobuf-compiler python-sphinx  ros-melodic-tf2-eigen libatlas-base-dev libsuitesparse-dev liblapack-dev
  3. sudo apt-get install -y python-wstool python-rosdep ninja-build stow 

1.2 安装cartographer、cartographer_ros和ceres_solver

1.2.1 初始化工作空间(这里与参考链接保持一致,命名为catkin_google_ws)

  1. mkdir catkin_google_ws
  2. cd catkin_google_ws
  3. wstool init src

1.2.2 从原作者的gitee上下载安装cartographer和cartographer_ros

  1. cd src

  2. git clone https://gitee.com/liu_xiao_eu/cartographer.git

  3. git clone https://gitee.com/liu_xiao_eu/cartographer_ros.git

1.2.3 在上述创建好的src文件夹下,获取ceres-solver源码

个人感觉没必要在src文件夹下安装,因为安装的ceres-solver会自动写入系统环境中,保持一致,我们在catkin_google_ws/src文件夹下,获取ceres-solver源码,版本要1.13.0

wget ceres-solver.org/ceres-solver-1.13.0.tar.gz

编译:

  1. cd ceres-solver-1.13.0
  2.  mkdir build
  3. cd build
  4. cmake ..
  5. make
测试一下,然后安装
  1. make test
  2. sudo make install

1.2.4 安装cartographer_ros的依赖项(proto3)

工作空间下打开终端输入:

src/cartographer/scripts/install_proto3.sh

1.2.5 安装cartographer_ros的依赖(安装ros时已经执行过没有问题,所以直接进行下一步骤)

  1. sudo rosdep init
  2. rosdep update
  3. rosdep install

1.2.6 安装absell-cpp library,方法同步骤1.2.4,在终端中输入:

src/cartographer/scripts/install_abseil.sh

1.2.7 编译Cartographer

catkin_make_isolated --install --use-ninja

值得一提的是,在catkin_google_ws工作空间打开终端,刷新环境变量语句是:

source install_isolated/setup.bash

注:安装过程未尽事宜可以参照上面的链接。

2 Cartographer 3D在线建图

2.1 基础介绍

基本使用Cartographer需要对三种文件有一个基本了解,即urdf、.lua、.launch文件,下面对这三种文件展开介绍。

2.1.1 urdf

简单讲一下,Cartographer需要机器人体包括传感器之间的tf坐标树,在其文件目录中有一个单独的urdf文件夹,我们可以在该目录下创建自己的urdf模型。笔者直接在仿真环境中加载了xacro,所以就没有去构建urdf模型,后续在launch文件中对这一部分进行了注释。

 2.1.2 .lua文件

笔者理解该文件是一种配置文件,可以对算法参数进行设置。例如我们进行3D建图,需要用到其中的backpack_3d.lua文件,我们就可以复制该文件然后添加到同一目录下,改个名字,例如叫做xxx_3d.lua。

下面是笔者的xxx_3d.lua文件内容:

  1. include "map_builder.lua"
  2. include "trajectory_builder.lua"
  3. options = {
  4. map_builder = MAP_BUILDER,
  5. trajectory_builder = TRAJECTORY_BUILDER,
  6. map_frame = "map",
  7. tracking_frame = "imu",
  8. published_frame = "base_footprint",
  9. odom_frame = "odom",
  10. provide_odom_frame = false,
  11. publish_frame_projected_to_2d = false,
  12. use_odometry = false,
  13. use_nav_sat = false,
  14. use_landmarks = false,
  15. num_laser_scans = 0,
  16. num_multi_echo_laser_scans = 0,
  17. num_subdivisions_per_laser_scan = 1,
  18. num_point_clouds = 1,
  19. lookup_transform_timeout_sec = 0.2,
  20. submap_publish_period_sec = 0.3,
  21. pose_publish_period_sec = 5e-3,
  22. trajectory_publish_period_sec = 30e-3,
  23. rangefinder_sampling_ratio = 1.,
  24. odometry_sampling_ratio = 1.,
  25. fixed_frame_pose_sampling_ratio = 1.,
  26. imu_sampling_ratio = 1.,
  27. landmarks_sampling_ratio = 1.,
  28. }
  29. TRAJECTORY_BUILDER_3D.num_accumulated_range_data = 1
  30. TRAJECTORY_BUILDER_3D.min_range = 0.2
  31. TRAJECTORY_BUILDER_3D.max_range = 150
  32. TRAJECTORY_BUILDER_2D.min_z = 0.1
  33. TRAJECTORY_BUILDER_2D.max_z = 1.0
  34. TRAJECTORY_BUILDER_3D.use_online_correlative_scan_matching = false
  35. MAP_BUILDER.use_trajectory_builder_3d = true
  36. MAP_BUILDER.num_background_threads = 4
  37. POSE_GRAPH.optimization_problem.huber_scale = 5e2
  38. POSE_GRAPH.optimize_every_n_nodes = 320
  39. POSE_GRAPH.constraint_builder.sampling_ratio = 0.03
  40. POSE_GRAPH.optimization_problem.ceres_solver_options.max_num_iterations = 20
  41. POSE_GRAPH.constraint_builder.min_score = 0.5
  42. POSE_GRAPH.constraint_builder.global_localization_min_score = 0.55
  43. POSE_GRAPH.optimization_problem.odometry_translation_weight = 1e3
  44. POSE_GRAPH.optimization_problem.odometry_rotation_weight = 1e3
  45. return options

其中参数设置原理可以参照下面的链接:

https://zhuanlan.zhihu.com/p/563264225icon-default.png?t=M85Bhttps://zhuanlan.zhihu.com/p/563264225

2.1.3 .launch文件

与.lua文件操作相同,我们在这里创建属于自己的launch文件,命名为xxx_3d.launch。

下面是笔者的xxx_3d.launch文件内容:

  1. <launch>
  2. <param name="/use_sim_time" value="true" />
  3. <!-- <param name="robot_description"
  4. textfile="$(find cartographer_ros)/urdf/wangchao_3d.urdf" /> -->
  5. <!-- <node name="robot_state_publisher" pkg="robot_state_publisher"
  6. type="robot_state_publisher" /> -->
  7. <node name="cartographer_node" pkg="cartographer_ros"
  8. type="cartographer_node" args="
  9. -configuration_directory $(find cartographer_ros)/configuration_files
  10. -configuration_basename xxx_3d.lua"
  11. output="screen">
  12. <remap from="points2" to="/velodyne_points" />
  13. <remap from="imu" to="/imu/data" />
  14. <remap from="/odom" to="/odom" />
  15. </node>
  16. <node name="cartographer_occupancy_grid_node" pkg="cartographer_ros"
  17. type="cartographer_occupancy_grid_node" args="-resolution 0.05" />
  18. <node name="rviz" pkg="rviz" type="rviz" required="true"
  19. args="-d $(find cartographer_ros)/configuration_files/demo_3d.rviz" />
  20. </launch>

注:笔者是在仿真环境中进行实验,所以use_sim_time设置为true,并注释了原算法自带的urdf模型代码,点云话题、IMU话题结合自己的实际情况进行修改。此次介绍中.lua和.launch文件仅适用于3D情况。

2.2 Cartographer 3D在线建图

2.2.1 加载仿真实验环境

2.2.2 启动Cartographer在线3D建图

roslaunch cartographer_ros xxx_3d.launch

启动launch文件前,不要忘记刷新一下环境变量。建图结果如图所示:

 tf坐标树关系如下:

 注:虽然Cartographer实现了在线建图和定位,但是/odom话题发布和Cartographer没有关系。想要查看Cartographer发布的位姿话题需要我们自行发布,笔者这里发布了carto_odom,来查看Cartographer的定位信息,这将在后续的纯定位环节展开介绍。

 2.2.3 地图保存

Cartographer创建的地图格式与Gmapping、Hector_slam不同,无法调用map_saver节点保存地图,需要以下命令:

首先需要在Cartographer工作空间下打开终端,刷新一下环境变量:

source install_isolated/setup.bash

然后请求/finish_trajectory服务,完成轨迹,不再接收数据,在终端中输入

rosservice call /finish_trajectory 0

请求/write_state服务,保存当前状态,其中路径可以根据需要自行更改,在终端中输入

rosservice call /write_state "{filename: '${HOME}/Downloads/mymap.pbstream'}"

笔者当时参考的链接:

https://www.cnblogs.com/54lwl/articles/14713852.htmlicon-default.png?t=M85Bhttps://www.cnblogs.com/54lwl/articles/14713852.html

3 Cartographer 3D纯定位

3.1 基础配置

见放一下笔者当时参考的链接:

https://blog.csdn.net/qq_40216084/article/details/106086066icon-default.png?t=M85Bhttps://blog.csdn.net/qq_40216084/article/details/106086066注:上面的链接修改了算法中子地图存储数量和构成一次回环的有效帧数量,避免地图覆盖问题,通过减少有效帧数量可以增加回环检测次数,但也增加了计算消耗,读者可以自行调节。

当然保持算法默认参数也是可以的,就只需要参照链接进行如下这步修改,即可使用纯定位:

 在这里说一下笔者遇到的特殊情况,因为是仿真环境,笔者的tf树关系如图所示:

刷新后:

xacro模型是没有问题的,问题应该出现在加载差速运动模型xacro时,左右轮和根节点base_footprint的关系由gazebo进行坐标变换发布。

 出于此原因,笔者将xxx.lua文件中published_frame 改成了 "odom",稳定了算法纯定位的实现,机器人模型不再跳动。

  1. options = {
  2. map_builder = MAP_BUILDER,
  3. trajectory_builder = TRAJECTORY_BUILDER,
  4. map_frame = "map",
  5. tracking_frame = "imu",
  6. published_frame = "odom",
  7. odom_frame = "odom",
  8. provide_odom_frame = false,
  9. publish_frame_projected_to_2d = false,
  10. use_odometry = false,
  11. use_nav_sat = false,
  12. use_landmarks = false,
  13. num_laser_scans = 0,
  14. num_multi_echo_laser_scans = 0,
  15. num_subdivisions_per_laser_scan = 1,
  16. num_point_clouds = 1,
  17. lookup_transform_timeout_sec = 0.2,
  18. submap_publish_period_sec = 0.3,
  19. pose_publish_period_sec = 5e-3,
  20. trajectory_publish_period_sec = 30e-3,
  21. rangefinder_sampling_ratio = 1.,
  22. odometry_sampling_ratio = 1.,
  23. fixed_frame_pose_sampling_ratio = 1.,
  24. imu_sampling_ratio = 1.,
  25. landmarks_sampling_ratio = 1.,
  26. }

 3.2 运行及结果

roslaunch cartographer_ros xxx_3d.launch load_state_filename:=/homw/xxx/Downloads/mymap1.pbstream

3.2.1 Cartographer纯定位结果

目录

1 Cartographer安装(Ubuntu8.04 melodic)

1.1 安装依赖包

1.2 安装cartographer、cartographer_ros和ceres_solver

1.2.1 初始化工作空间(这里与参考链接保持一致,命名为catkin_google_ws)

1.2.2 从原作者的gitee上下载安装cartographer和cartographer_ros

1.2.3 在上述创建好的src文件夹下,获取ceres-solver源码

1.2.4 安装cartographer_ros的依赖项(proto3)

1.2.5 安装cartographer_ros的依赖(安装ros时已经执行过没有问题,所以直接进行下一步骤)

1.2.6 安装absell-cpp library,方法同步骤1.2.4,在终端中输入:

1.2.7 编译Cartographer

2 Cartographer 3D在线建图

2.1 基础介绍

2.1.1 urdf

2.1.2 .lua文件

2.1.3 .launch文件

2.2 Cartographer 3D在线建图

2.2.1 加载仿真实验环境

2.2.2 启动Cartographer在线3D建图

2.2.3 地图保存

3 Cartographer 3D纯定位

3.1 基础配置

 3.2 运行及结果

3.2.1 Cartographer纯定位结果

3.2.2 与move_base结合

3.2.3 Gazebo中导航场景(到达目标点)

 3.3 定位话题发布

3.3.1 修改publish_tracked_pose为true

3.3.2 修改node.h文件

3.3.3 修改node.cc文件


3.2.3 Gazebo中导航场景(到达目标点)

 3.3 定位话题发布

写到这其实已经写不动了,但是前面留坑需要填。先放笔者当时参考的链接:

https://blog.csdn.net/zhaohaowu/article/details/120889458icon-default.png?t=M85Bhttps://blog.csdn.net/zhaohaowu/article/details/120889458笔者选择了方法1,但是上述代码存在部分问题,一些变量的声明应该是忘记给出了,所以一会直接放代码。

3.3.1 修改publish_tracked_pose为true

首先在VScode里面ctrl+f找到node.cc里面的node_options_.publish_tracked_pose,选中publish_tracked_pose按F12,跳转到定义处,在node_options.h文件下,可以看到publish_tracked_pose默认为false,将其修改为true,这样算法可以发布tracked_pose话题。

3.3.2 修改node.h文件

在node.h中,ctrl+f搜索tracked_pose_publisher_,在其下面添加::ros::Publisher pub,具体如图所示:

 3.3.3 修改node.cc文件

在第一个if (node_options_.publish_tracked_pose) 中加入:

pub = node_handle_.advertise<::nav_msgs::Odometry>("carto_odom", 100);

具体如图所示:

 在第二个if (node_options_.publish_tracked_pose) 中加入:

  1. current_time = ros::Time::now();
  2. double current_x = pose_msg.pose.position.x;
  3. double current_y = pose_msg.pose.position.y;
  4. double current_yaw = tf::getYaw(pose_msg.pose.orientation);
  5. double dt = (current_time - last_time).toSec();
  6. double dx = current_x - last_x;
  7. double dy = current_y - last_y;
  8. double d_yaw = current_yaw - last_yaw;
  9. double lin_speed = dx/dt;
  10. double ang_speed = d_yaw/dt;
  11. ::nav_msgs::Odometry msg;
  12. msg.header.stamp = ros::Time::now();
  13. msg.header.frame_id = "odom";
  14. msg.child_frame_id = "velodyne";
  15. msg.pose.pose.position = pose_msg.pose.position;
  16. msg.pose.pose.orientation = pose_msg.pose.orientation;
  17. msg.twist.twist.linear.x = lin_speed;
  18. msg.twist.twist.linear.y = 0.0;
  19. msg.twist.twist.angular.z = ang_speed;
  20. pub.publish(msg);
  21. last_time = ros::Time::now();
  22. double last_x = pose_msg.pose.position.x;
  23. double last_y = pose_msg.pose.position.y;
  24. double last_yaw = tf::getYaw(pose_msg.pose.orientation);

 具体如图所示:

 最后,在node.cc上方补充变量的定义:

 如果运行提示tf错误,可以在头文件中添加:

  1. #include "geometry_msgs/PoseWithCovarianceStamped.h"
  2. #include "tf/tf.h"

 附上完整的node.cc文件代码:

  1. /*
  2. * Copyright 2016 The Cartographer Authors
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include "cartographer_ros/node.h"
  17. #include <chrono>
  18. #include <string>
  19. #include <vector>
  20. #include "Eigen/Core"
  21. #include "absl/memory/memory.h"
  22. #include "absl/strings/str_cat.h"
  23. #include "cartographer/common/configuration_file_resolver.h"
  24. #include "cartographer/common/lua_parameter_dictionary.h"
  25. #include "cartographer/common/port.h"
  26. #include "cartographer/common/time.h"
  27. #include "cartographer/mapping/pose_graph_interface.h"
  28. #include "cartographer/mapping/proto/submap_visualization.pb.h"
  29. #include "cartographer/metrics/register.h"
  30. #include "cartographer/sensor/point_cloud.h"
  31. #include "cartographer/transform/rigid_transform.h"
  32. #include "cartographer/transform/transform.h"
  33. #include "cartographer_ros/metrics/family_factory.h"
  34. #include "cartographer_ros/msg_conversion.h"
  35. #include "cartographer_ros/sensor_bridge.h"
  36. #include "cartographer_ros/tf_bridge.h"
  37. #include "cartographer_ros/time_conversion.h"
  38. #include "cartographer_ros_msgs/StatusCode.h"
  39. #include "cartographer_ros_msgs/StatusResponse.h"
  40. #include "geometry_msgs/PoseStamped.h"
  41. #include "glog/logging.h"
  42. #include "nav_msgs/Odometry.h"
  43. #include "ros/serialization.h"
  44. #include "sensor_msgs/PointCloud2.h"
  45. #include "tf2_eigen/tf2_eigen.h"
  46. #include "visualization_msgs/MarkerArray.h"
  47. //add
  48. ros::Time current_time;
  49. ros::Time last_time;
  50. double last_yaw = 0;
  51. double last_x = 0;
  52. double last_y = 0;
  53. namespace cartographer_ros {
  54. namespace carto = ::cartographer;
  55. using carto::transform::Rigid3d;
  56. using TrajectoryState =
  57. ::cartographer::mapping::PoseGraphInterface::TrajectoryState;
  58. namespace {
  59. // Subscribes to the 'topic' for 'trajectory_id' using the 'node_handle' and
  60. // calls 'handler' on the 'node' to handle messages. Returns the subscriber.
  61. template <typename MessageType>
  62. ::ros::Subscriber SubscribeWithHandler(
  63. void (Node::*handler)(int, const std::string&,
  64. const typename MessageType::ConstPtr&),
  65. const int trajectory_id, const std::string& topic,
  66. ::ros::NodeHandle* const node_handle, Node* const node) {
  67. return node_handle->subscribe<MessageType>(
  68. topic, kInfiniteSubscriberQueueSize,
  69. boost::function<void(const typename MessageType::ConstPtr&)>(
  70. [node, handler, trajectory_id,
  71. topic](const typename MessageType::ConstPtr& msg) {
  72. (node->*handler)(trajectory_id, topic, msg);
  73. }));
  74. }
  75. std::string TrajectoryStateToString(const TrajectoryState trajectory_state) {
  76. switch (trajectory_state) {
  77. case TrajectoryState::ACTIVE:
  78. return "ACTIVE";
  79. case TrajectoryState::FINISHED:
  80. return "FINISHED";
  81. case TrajectoryState::FROZEN:
  82. return "FROZEN";
  83. case TrajectoryState::DELETED:
  84. return "DELETED";
  85. }
  86. return "";
  87. }
  88. } // namespace
  89. Node::Node(
  90. const NodeOptions& node_options,
  91. std::unique_ptr<cartographer::mapping::MapBuilderInterface> map_builder,
  92. tf2_ros::Buffer* const tf_buffer, const bool collect_metrics)
  93. : node_options_(node_options),
  94. map_builder_bridge_(node_options_, std::move(map_builder), tf_buffer) {
  95. absl::MutexLock lock(&mutex_);
  96. if (collect_metrics) {
  97. metrics_registry_ = absl::make_unique<metrics::FamilyFactory>();
  98. carto::metrics::RegisterAllMetrics(metrics_registry_.get());
  99. }
  100. submap_list_publisher_ =
  101. node_handle_.advertise<::cartographer_ros_msgs::SubmapList>(
  102. kSubmapListTopic, kLatestOnlyPublisherQueueSize);
  103. trajectory_node_list_publisher_ =
  104. node_handle_.advertise<::visualization_msgs::MarkerArray>(
  105. kTrajectoryNodeListTopic, kLatestOnlyPublisherQueueSize);
  106. landmark_poses_list_publisher_ =
  107. node_handle_.advertise<::visualization_msgs::MarkerArray>(
  108. kLandmarkPosesListTopic, kLatestOnlyPublisherQueueSize);
  109. constraint_list_publisher_ =
  110. node_handle_.advertise<::visualization_msgs::MarkerArray>(
  111. kConstraintListTopic, kLatestOnlyPublisherQueueSize);
  112. if (node_options_.publish_tracked_pose) {
  113. tracked_pose_publisher_ =
  114. node_handle_.advertise<::geometry_msgs::PoseStamped>(
  115. kTrackedPoseTopic, kLatestOnlyPublisherQueueSize);
  116. //add
  117. pub = node_handle_.advertise<::nav_msgs::Odometry>("carto_odom", 100);
  118. }
  119. service_servers_.push_back(node_handle_.advertiseService(
  120. kSubmapQueryServiceName, &Node::HandleSubmapQuery, this));
  121. service_servers_.push_back(node_handle_.advertiseService(
  122. kTrajectoryQueryServiceName, &Node::HandleTrajectoryQuery, this));
  123. service_servers_.push_back(node_handle_.advertiseService(
  124. kStartTrajectoryServiceName, &Node::HandleStartTrajectory, this));
  125. service_servers_.push_back(node_handle_.advertiseService(
  126. kFinishTrajectoryServiceName, &Node::HandleFinishTrajectory, this));
  127. service_servers_.push_back(node_handle_.advertiseService(
  128. kWriteStateServiceName, &Node::HandleWriteState, this));
  129. service_servers_.push_back(node_handle_.advertiseService(
  130. kGetTrajectoryStatesServiceName, &Node::HandleGetTrajectoryStates, this));
  131. service_servers_.push_back(node_handle_.advertiseService(
  132. kReadMetricsServiceName, &Node::HandleReadMetrics, this));
  133. scan_matched_point_cloud_publisher_ =
  134. node_handle_.advertise<sensor_msgs::PointCloud2>(
  135. kScanMatchedPointCloudTopic, kLatestOnlyPublisherQueueSize);
  136. wall_timers_.push_back(node_handle_.createWallTimer(
  137. ::ros::WallDuration(node_options_.submap_publish_period_sec),
  138. &Node::PublishSubmapList, this));
  139. if (node_options_.pose_publish_period_sec > 0) {
  140. publish_local_trajectory_data_timer_ = node_handle_.createTimer(
  141. ::ros::Duration(node_options_.pose_publish_period_sec),
  142. &Node::PublishLocalTrajectoryData, this);
  143. }
  144. wall_timers_.push_back(node_handle_.createWallTimer(
  145. ::ros::WallDuration(node_options_.trajectory_publish_period_sec),
  146. &Node::PublishTrajectoryNodeList, this));
  147. wall_timers_.push_back(node_handle_.createWallTimer(
  148. ::ros::WallDuration(node_options_.trajectory_publish_period_sec),
  149. &Node::PublishLandmarkPosesList, this));
  150. wall_timers_.push_back(node_handle_.createWallTimer(
  151. ::ros::WallDuration(kConstraintPublishPeriodSec),
  152. &Node::PublishConstraintList, this));
  153. }
  154. Node::~Node() { FinishAllTrajectories(); }
  155. ::ros::NodeHandle* Node::node_handle() { return &node_handle_; }
  156. bool Node::HandleSubmapQuery(
  157. ::cartographer_ros_msgs::SubmapQuery::Request& request,
  158. ::cartographer_ros_msgs::SubmapQuery::Response& response) {
  159. absl::MutexLock lock(&mutex_);
  160. map_builder_bridge_.HandleSubmapQuery(request, response);
  161. return true;
  162. }
  163. bool Node::HandleTrajectoryQuery(
  164. ::cartographer_ros_msgs::TrajectoryQuery::Request& request,
  165. ::cartographer_ros_msgs::TrajectoryQuery::Response& response) {
  166. absl::MutexLock lock(&mutex_);
  167. response.status = TrajectoryStateToStatus(
  168. request.trajectory_id,
  169. {TrajectoryState::ACTIVE, TrajectoryState::FINISHED,
  170. TrajectoryState::FROZEN} /* valid states */);
  171. if (response.status.code != cartographer_ros_msgs::StatusCode::OK) {
  172. LOG(ERROR) << "Can't query trajectory from pose graph: "
  173. << response.status.message;
  174. return true;
  175. }
  176. map_builder_bridge_.HandleTrajectoryQuery(request, response);
  177. return true;
  178. }
  179. void Node::PublishSubmapList(const ::ros::WallTimerEvent& unused_timer_event) {
  180. absl::MutexLock lock(&mutex_);
  181. submap_list_publisher_.publish(map_builder_bridge_.GetSubmapList());
  182. }
  183. void Node::AddExtrapolator(const int trajectory_id,
  184. const TrajectoryOptions& options) {
  185. constexpr double kExtrapolationEstimationTimeSec = 0.001; // 1 ms
  186. CHECK(extrapolators_.count(trajectory_id) == 0);
  187. const double gravity_time_constant =
  188. node_options_.map_builder_options.use_trajectory_builder_3d()
  189. ? options.trajectory_builder_options.trajectory_builder_3d_options()
  190. .imu_gravity_time_constant()
  191. : options.trajectory_builder_options.trajectory_builder_2d_options()
  192. .imu_gravity_time_constant();
  193. extrapolators_.emplace(
  194. std::piecewise_construct, std::forward_as_tuple(trajectory_id),
  195. std::forward_as_tuple(
  196. ::cartographer::common::FromSeconds(kExtrapolationEstimationTimeSec),
  197. gravity_time_constant));
  198. }
  199. void Node::AddSensorSamplers(const int trajectory_id,
  200. const TrajectoryOptions& options) {
  201. CHECK(sensor_samplers_.count(trajectory_id) == 0);
  202. sensor_samplers_.emplace(
  203. std::piecewise_construct, std::forward_as_tuple(trajectory_id),
  204. std::forward_as_tuple(
  205. options.rangefinder_sampling_ratio, options.odometry_sampling_ratio,
  206. options.fixed_frame_pose_sampling_ratio, options.imu_sampling_ratio,
  207. options.landmarks_sampling_ratio));
  208. }
  209. void Node::PublishLocalTrajectoryData(const ::ros::TimerEvent& timer_event) {
  210. absl::MutexLock lock(&mutex_);
  211. for (const auto& entry : map_builder_bridge_.GetLocalTrajectoryData()) {
  212. const auto& trajectory_data = entry.second;
  213. auto& extrapolator = extrapolators_.at(entry.first);
  214. // We only publish a point cloud if it has changed. It is not needed at high
  215. // frequency, and republishing it would be computationally wasteful.
  216. if (trajectory_data.local_slam_data->time !=
  217. extrapolator.GetLastPoseTime()) {
  218. if (scan_matched_point_cloud_publisher_.getNumSubscribers() > 0) {
  219. // TODO(gaschler): Consider using other message without time
  220. // information.
  221. carto::sensor::TimedPointCloud point_cloud;
  222. point_cloud.reserve(trajectory_data.local_slam_data->range_data_in_local
  223. .returns.size());
  224. for (const cartographer::sensor::RangefinderPoint point :
  225. trajectory_data.local_slam_data->range_data_in_local.returns) {
  226. point_cloud.push_back(cartographer::sensor::ToTimedRangefinderPoint(
  227. point, 0.f /* time */));
  228. }
  229. scan_matched_point_cloud_publisher_.publish(ToPointCloud2Message(
  230. carto::common::ToUniversal(trajectory_data.local_slam_data->time),
  231. node_options_.map_frame,
  232. carto::sensor::TransformTimedPointCloud(
  233. point_cloud, trajectory_data.local_to_map.cast<float>())));
  234. }
  235. extrapolator.AddPose(trajectory_data.local_slam_data->time,
  236. trajectory_data.local_slam_data->local_pose);
  237. }
  238. geometry_msgs::TransformStamped stamped_transform;
  239. // If we do not publish a new point cloud, we still allow time of the
  240. // published poses to advance. If we already know a newer pose, we use its
  241. // time instead. Since tf knows how to interpolate, providing newer
  242. // information is better.
  243. const ::cartographer::common::Time now = std::max(
  244. FromRos(ros::Time::now()), extrapolator.GetLastExtrapolatedTime());
  245. stamped_transform.header.stamp =
  246. node_options_.use_pose_extrapolator
  247. ? ToRos(now)
  248. : ToRos(trajectory_data.local_slam_data->time);
  249. // Suppress publishing if we already published a transform at this time.
  250. // Due to 2020-07 changes to geometry2, tf buffer will issue warnings for
  251. // repeated transforms with the same timestamp.
  252. if (last_published_tf_stamps_.count(entry.first) &&
  253. last_published_tf_stamps_[entry.first] == stamped_transform.header.stamp)
  254. continue;
  255. last_published_tf_stamps_[entry.first] = stamped_transform.header.stamp;
  256. const Rigid3d tracking_to_local_3d =
  257. node_options_.use_pose_extrapolator
  258. ? extrapolator.ExtrapolatePose(now)
  259. : trajectory_data.local_slam_data->local_pose;
  260. const Rigid3d tracking_to_local = [&] {
  261. if (trajectory_data.trajectory_options.publish_frame_projected_to_2d) {
  262. return carto::transform::Embed3D(
  263. carto::transform::Project2D(tracking_to_local_3d));
  264. }
  265. return tracking_to_local_3d;
  266. }();
  267. const Rigid3d tracking_to_map =
  268. trajectory_data.local_to_map * tracking_to_local;
  269. if (trajectory_data.published_to_tracking != nullptr) {
  270. if (node_options_.publish_to_tf) {
  271. if (trajectory_data.trajectory_options.provide_odom_frame) {
  272. std::vector<geometry_msgs::TransformStamped> stamped_transforms;
  273. stamped_transform.header.frame_id = node_options_.map_frame;
  274. stamped_transform.child_frame_id =
  275. trajectory_data.trajectory_options.odom_frame;
  276. stamped_transform.transform =
  277. ToGeometryMsgTransform(trajectory_data.local_to_map);
  278. stamped_transforms.push_back(stamped_transform);
  279. stamped_transform.header.frame_id =
  280. trajectory_data.trajectory_options.odom_frame;
  281. stamped_transform.child_frame_id =
  282. trajectory_data.trajectory_options.published_frame;
  283. stamped_transform.transform = ToGeometryMsgTransform(
  284. tracking_to_local * (*trajectory_data.published_to_tracking));
  285. stamped_transforms.push_back(stamped_transform);
  286. tf_broadcaster_.sendTransform(stamped_transforms);
  287. } else {
  288. stamped_transform.header.frame_id = node_options_.map_frame;
  289. stamped_transform.child_frame_id =
  290. trajectory_data.trajectory_options.published_frame;
  291. stamped_transform.transform = ToGeometryMsgTransform(
  292. tracking_to_map * (*trajectory_data.published_to_tracking));
  293. tf_broadcaster_.sendTransform(stamped_transform);
  294. }
  295. }
  296. if (node_options_.publish_tracked_pose) {
  297. ::geometry_msgs::PoseStamped pose_msg;
  298. pose_msg.header.frame_id = node_options_.map_frame;
  299. pose_msg.header.stamp = stamped_transform.header.stamp;
  300. pose_msg.pose = ToGeometryMsgPose(tracking_to_map);
  301. tracked_pose_publisher_.publish(pose_msg);
  302. //add
  303. current_time = ros::Time::now();
  304. double current_x = pose_msg.pose.position.x;
  305. double current_y = pose_msg.pose.position.y;
  306. double current_yaw = tf::getYaw(pose_msg.pose.orientation);
  307. double dt = (current_time - last_time).toSec();
  308. double dx = current_x - last_x;
  309. double dy = current_y - last_y;
  310. double d_yaw = current_yaw - last_yaw;
  311. double lin_speed = dx/dt;
  312. double ang_speed = d_yaw/dt;
  313. ::nav_msgs::Odometry msg;
  314. msg.header.stamp = ros::Time::now();
  315. msg.header.frame_id = "odom";
  316. msg.child_frame_id = "velodyne";
  317. msg.pose.pose.position = pose_msg.pose.position;
  318. msg.pose.pose.orientation = pose_msg.pose.orientation;
  319. msg.twist.twist.linear.x = lin_speed;
  320. msg.twist.twist.linear.y = 0.0;
  321. msg.twist.twist.angular.z = ang_speed;
  322. pub.publish(msg);
  323. last_time = ros::Time::now();
  324. double last_x = pose_msg.pose.position.x;
  325. double last_y = pose_msg.pose.position.y;
  326. double last_yaw = tf::getYaw(pose_msg.pose.orientation);
  327. }
  328. }
  329. }
  330. }
  331. void Node::PublishTrajectoryNodeList(
  332. const ::ros::WallTimerEvent& unused_timer_event) {
  333. if (trajectory_node_list_publisher_.getNumSubscribers() > 0) {
  334. absl::MutexLock lock(&mutex_);
  335. trajectory_node_list_publisher_.publish(
  336. map_builder_bridge_.GetTrajectoryNodeList());
  337. }
  338. }
  339. void Node::PublishLandmarkPosesList(
  340. const ::ros::WallTimerEvent& unused_timer_event) {
  341. if (landmark_poses_list_publisher_.getNumSubscribers() > 0) {
  342. absl::MutexLock lock(&mutex_);
  343. landmark_poses_list_publisher_.publish(
  344. map_builder_bridge_.GetLandmarkPosesList());
  345. }
  346. }
  347. void Node::PublishConstraintList(
  348. const ::ros::WallTimerEvent& unused_timer_event) {
  349. if (constraint_list_publisher_.getNumSubscribers() > 0) {
  350. absl::MutexLock lock(&mutex_);
  351. constraint_list_publisher_.publish(map_builder_bridge_.GetConstraintList());
  352. }
  353. }
  354. std::set<cartographer::mapping::TrajectoryBuilderInterface::SensorId>
  355. Node::ComputeExpectedSensorIds(const TrajectoryOptions& options) const {
  356. using SensorId = cartographer::mapping::TrajectoryBuilderInterface::SensorId;
  357. using SensorType = SensorId::SensorType;
  358. std::set<SensorId> expected_topics;
  359. // Subscribe to all laser scan, multi echo laser scan, and point cloud topics.
  360. for (const std::string& topic :
  361. ComputeRepeatedTopicNames(kLaserScanTopic, options.num_laser_scans)) {
  362. expected_topics.insert(SensorId{SensorType::RANGE, topic});
  363. }
  364. for (const std::string& topic : ComputeRepeatedTopicNames(
  365. kMultiEchoLaserScanTopic, options.num_multi_echo_laser_scans)) {
  366. expected_topics.insert(SensorId{SensorType::RANGE, topic});
  367. }
  368. for (const std::string& topic :
  369. ComputeRepeatedTopicNames(kPointCloud2Topic, options.num_point_clouds)) {
  370. expected_topics.insert(SensorId{SensorType::RANGE, topic});
  371. }
  372. // For 2D SLAM, subscribe to the IMU if we expect it. For 3D SLAM, the IMU is
  373. // required.
  374. if (node_options_.map_builder_options.use_trajectory_builder_3d() ||
  375. (node_options_.map_builder_options.use_trajectory_builder_2d() &&
  376. options.trajectory_builder_options.trajectory_builder_2d_options()
  377. .use_imu_data())) {
  378. expected_topics.insert(SensorId{SensorType::IMU, kImuTopic});
  379. }
  380. // Odometry is optional.
  381. if (options.use_odometry) {
  382. expected_topics.insert(SensorId{SensorType::ODOMETRY, kOdometryTopic});
  383. }
  384. // NavSatFix is optional.
  385. if (options.use_nav_sat) {
  386. expected_topics.insert(
  387. SensorId{SensorType::FIXED_FRAME_POSE, kNavSatFixTopic});
  388. }
  389. // Landmark is optional.
  390. if (options.use_landmarks) {
  391. expected_topics.insert(SensorId{SensorType::LANDMARK, kLandmarkTopic});
  392. }
  393. return expected_topics;
  394. }
  395. int Node::AddTrajectory(const TrajectoryOptions& options) {
  396. const std::set<cartographer::mapping::TrajectoryBuilderInterface::SensorId>
  397. expected_sensor_ids = ComputeExpectedSensorIds(options);
  398. const int trajectory_id =
  399. map_builder_bridge_.AddTrajectory(expected_sensor_ids, options);
  400. AddExtrapolator(trajectory_id, options);
  401. AddSensorSamplers(trajectory_id, options);
  402. LaunchSubscribers(options, trajectory_id);
  403. wall_timers_.push_back(node_handle_.createWallTimer(
  404. ::ros::WallDuration(kTopicMismatchCheckDelaySec),
  405. &Node::MaybeWarnAboutTopicMismatch, this, /*oneshot=*/true));
  406. for (const auto& sensor_id : expected_sensor_ids) {
  407. subscribed_topics_.insert(sensor_id.id);
  408. }
  409. return trajectory_id;
  410. }
  411. void Node::LaunchSubscribers(const TrajectoryOptions& options,
  412. const int trajectory_id) {
  413. for (const std::string& topic :
  414. ComputeRepeatedTopicNames(kLaserScanTopic, options.num_laser_scans)) {
  415. subscribers_[trajectory_id].push_back(
  416. {SubscribeWithHandler<sensor_msgs::LaserScan>(
  417. &Node::HandleLaserScanMessage, trajectory_id, topic, &node_handle_,
  418. this),
  419. topic});
  420. }
  421. for (const std::string& topic : ComputeRepeatedTopicNames(
  422. kMultiEchoLaserScanTopic, options.num_multi_echo_laser_scans)) {
  423. subscribers_[trajectory_id].push_back(
  424. {SubscribeWithHandler<sensor_msgs::MultiEchoLaserScan>(
  425. &Node::HandleMultiEchoLaserScanMessage, trajectory_id, topic,
  426. &node_handle_, this),
  427. topic});
  428. }
  429. for (const std::string& topic :
  430. ComputeRepeatedTopicNames(kPointCloud2Topic, options.num_point_clouds)) {
  431. subscribers_[trajectory_id].push_back(
  432. {SubscribeWithHandler<sensor_msgs::PointCloud2>(
  433. &Node::HandlePointCloud2Message, trajectory_id, topic,
  434. &node_handle_, this),
  435. topic});
  436. }
  437. // For 2D SLAM, subscribe to the IMU if we expect it. For 3D SLAM, the IMU is
  438. // required.
  439. if (node_options_.map_builder_options.use_trajectory_builder_3d() ||
  440. (node_options_.map_builder_options.use_trajectory_builder_2d() &&
  441. options.trajectory_builder_options.trajectory_builder_2d_options()
  442. .use_imu_data())) {
  443. subscribers_[trajectory_id].push_back(
  444. {SubscribeWithHandler<sensor_msgs::Imu>(&Node::HandleImuMessage,
  445. trajectory_id, kImuTopic,
  446. &node_handle_, this),
  447. kImuTopic});
  448. }
  449. if (options.use_odometry) {
  450. subscribers_[trajectory_id].push_back(
  451. {SubscribeWithHandler<nav_msgs::Odometry>(&Node::HandleOdometryMessage,
  452. trajectory_id, kOdometryTopic,
  453. &node_handle_, this),
  454. kOdometryTopic});
  455. }
  456. if (options.use_nav_sat) {
  457. subscribers_[trajectory_id].push_back(
  458. {SubscribeWithHandler<sensor_msgs::NavSatFix>(
  459. &Node::HandleNavSatFixMessage, trajectory_id, kNavSatFixTopic,
  460. &node_handle_, this),
  461. kNavSatFixTopic});
  462. }
  463. if (options.use_landmarks) {
  464. subscribers_[trajectory_id].push_back(
  465. {SubscribeWithHandler<cartographer_ros_msgs::LandmarkList>(
  466. &Node::HandleLandmarkMessage, trajectory_id, kLandmarkTopic,
  467. &node_handle_, this),
  468. kLandmarkTopic});
  469. }
  470. }
  471. bool Node::ValidateTrajectoryOptions(const TrajectoryOptions& options) {
  472. if (node_options_.map_builder_options.use_trajectory_builder_2d()) {
  473. return options.trajectory_builder_options
  474. .has_trajectory_builder_2d_options();
  475. }
  476. if (node_options_.map_builder_options.use_trajectory_builder_3d()) {
  477. return options.trajectory_builder_options
  478. .has_trajectory_builder_3d_options();
  479. }
  480. return false;
  481. }
  482. bool Node::ValidateTopicNames(const TrajectoryOptions& options) {
  483. for (const auto& sensor_id : ComputeExpectedSensorIds(options)) {
  484. const std::string& topic = sensor_id.id;
  485. if (subscribed_topics_.count(topic) > 0) {
  486. LOG(ERROR) << "Topic name [" << topic << "] is already used.";
  487. return false;
  488. }
  489. }
  490. return true;
  491. }
  492. cartographer_ros_msgs::StatusResponse Node::TrajectoryStateToStatus(
  493. const int trajectory_id, const std::set<TrajectoryState>& valid_states) {
  494. const auto trajectory_states = map_builder_bridge_.GetTrajectoryStates();
  495. cartographer_ros_msgs::StatusResponse status_response;
  496. const auto it = trajectory_states.find(trajectory_id);
  497. if (it == trajectory_states.end()) {
  498. status_response.message =
  499. absl::StrCat("Trajectory ", trajectory_id, " doesn't exist.");
  500. status_response.code = cartographer_ros_msgs::StatusCode::NOT_FOUND;
  501. return status_response;
  502. }
  503. status_response.message =
  504. absl::StrCat("Trajectory ", trajectory_id, " is in '",
  505. TrajectoryStateToString(it->second), "' state.");
  506. status_response.code =
  507. valid_states.count(it->second)
  508. ? cartographer_ros_msgs::StatusCode::OK
  509. : cartographer_ros_msgs::StatusCode::INVALID_ARGUMENT;
  510. return status_response;
  511. }
  512. cartographer_ros_msgs::StatusResponse Node::FinishTrajectoryUnderLock(
  513. const int trajectory_id) {
  514. cartographer_ros_msgs::StatusResponse status_response;
  515. if (trajectories_scheduled_for_finish_.count(trajectory_id)) {
  516. status_response.message = absl::StrCat("Trajectory ", trajectory_id,
  517. " already pending to finish.");
  518. status_response.code = cartographer_ros_msgs::StatusCode::OK;
  519. LOG(INFO) << status_response.message;
  520. return status_response;
  521. }
  522. // First, check if we can actually finish the trajectory.
  523. status_response = TrajectoryStateToStatus(
  524. trajectory_id, {TrajectoryState::ACTIVE} /* valid states */);
  525. if (status_response.code != cartographer_ros_msgs::StatusCode::OK) {
  526. LOG(ERROR) << "Can't finish trajectory: " << status_response.message;
  527. return status_response;
  528. }
  529. // Shutdown the subscribers of this trajectory.
  530. // A valid case with no subscribers is e.g. if we just visualize states.
  531. if (subscribers_.count(trajectory_id)) {
  532. for (auto& entry : subscribers_[trajectory_id]) {
  533. entry.subscriber.shutdown();
  534. subscribed_topics_.erase(entry.topic);
  535. LOG(INFO) << "Shutdown the subscriber of [" << entry.topic << "]";
  536. }
  537. CHECK_EQ(subscribers_.erase(trajectory_id), 1);
  538. }
  539. map_builder_bridge_.FinishTrajectory(trajectory_id);
  540. trajectories_scheduled_for_finish_.emplace(trajectory_id);
  541. status_response.message =
  542. absl::StrCat("Finished trajectory ", trajectory_id, ".");
  543. status_response.code = cartographer_ros_msgs::StatusCode::OK;
  544. return status_response;
  545. }
  546. bool Node::HandleStartTrajectory(
  547. ::cartographer_ros_msgs::StartTrajectory::Request& request,
  548. ::cartographer_ros_msgs::StartTrajectory::Response& response) {
  549. TrajectoryOptions trajectory_options;
  550. std::tie(std::ignore, trajectory_options) = LoadOptions(
  551. request.configuration_directory, request.configuration_basename);
  552. if (request.use_initial_pose) {
  553. const auto pose = ToRigid3d(request.initial_pose);
  554. if (!pose.IsValid()) {
  555. response.status.message =
  556. "Invalid pose argument. Orientation quaternion must be normalized.";
  557. LOG(ERROR) << response.status.message;
  558. response.status.code =
  559. cartographer_ros_msgs::StatusCode::INVALID_ARGUMENT;
  560. return true;
  561. }
  562. // Check if the requested trajectory for the relative initial pose exists.
  563. response.status = TrajectoryStateToStatus(
  564. request.relative_to_trajectory_id,
  565. {TrajectoryState::ACTIVE, TrajectoryState::FROZEN,
  566. TrajectoryState::FINISHED} /* valid states */);
  567. if (response.status.code != cartographer_ros_msgs::StatusCode::OK) {
  568. LOG(ERROR) << "Can't start a trajectory with initial pose: "
  569. << response.status.message;
  570. return true;
  571. }
  572. ::cartographer::mapping::proto::InitialTrajectoryPose
  573. initial_trajectory_pose;
  574. initial_trajectory_pose.set_to_trajectory_id(
  575. request.relative_to_trajectory_id);
  576. *initial_trajectory_pose.mutable_relative_pose() =
  577. cartographer::transform::ToProto(pose);
  578. initial_trajectory_pose.set_timestamp(cartographer::common::ToUniversal(
  579. ::cartographer_ros::FromRos(ros::Time(0))));
  580. *trajectory_options.trajectory_builder_options
  581. .mutable_initial_trajectory_pose() = initial_trajectory_pose;
  582. }
  583. if (!ValidateTrajectoryOptions(trajectory_options)) {
  584. response.status.message = "Invalid trajectory options.";
  585. LOG(ERROR) << response.status.message;
  586. response.status.code = cartographer_ros_msgs::StatusCode::INVALID_ARGUMENT;
  587. } else if (!ValidateTopicNames(trajectory_options)) {
  588. response.status.message = "Topics are already used by another trajectory.";
  589. LOG(ERROR) << response.status.message;
  590. response.status.code = cartographer_ros_msgs::StatusCode::INVALID_ARGUMENT;
  591. } else {
  592. response.status.message = "Success.";
  593. response.trajectory_id = AddTrajectory(trajectory_options);
  594. response.status.code = cartographer_ros_msgs::StatusCode::OK;
  595. }
  596. return true;
  597. }
  598. void Node::StartTrajectoryWithDefaultTopics(const TrajectoryOptions& options) {
  599. absl::MutexLock lock(&mutex_);
  600. CHECK(ValidateTrajectoryOptions(options));
  601. AddTrajectory(options);
  602. }
  603. std::vector<
  604. std::set<cartographer::mapping::TrajectoryBuilderInterface::SensorId>>
  605. Node::ComputeDefaultSensorIdsForMultipleBags(
  606. const std::vector<TrajectoryOptions>& bags_options) const {
  607. using SensorId = cartographer::mapping::TrajectoryBuilderInterface::SensorId;
  608. std::vector<std::set<SensorId>> bags_sensor_ids;
  609. for (size_t i = 0; i < bags_options.size(); ++i) {
  610. std::string prefix;
  611. if (bags_options.size() > 1) {
  612. prefix = "bag_" + std::to_string(i + 1) + "_";
  613. }
  614. std::set<SensorId> unique_sensor_ids;
  615. for (const auto& sensor_id : ComputeExpectedSensorIds(bags_options.at(i))) {
  616. unique_sensor_ids.insert(SensorId{sensor_id.type, prefix + sensor_id.id});
  617. }
  618. bags_sensor_ids.push_back(unique_sensor_ids);
  619. }
  620. return bags_sensor_ids;
  621. }
  622. int Node::AddOfflineTrajectory(
  623. const std::set<cartographer::mapping::TrajectoryBuilderInterface::SensorId>&
  624. expected_sensor_ids,
  625. const TrajectoryOptions& options) {
  626. absl::MutexLock lock(&mutex_);
  627. const int trajectory_id =
  628. map_builder_bridge_.AddTrajectory(expected_sensor_ids, options);
  629. AddExtrapolator(trajectory_id, options);
  630. AddSensorSamplers(trajectory_id, options);
  631. return trajectory_id;
  632. }
  633. bool Node::HandleGetTrajectoryStates(
  634. ::cartographer_ros_msgs::GetTrajectoryStates::Request& request,
  635. ::cartographer_ros_msgs::GetTrajectoryStates::Response& response) {
  636. using TrajectoryState =
  637. ::cartographer::mapping::PoseGraphInterface::TrajectoryState;
  638. absl::MutexLock lock(&mutex_);
  639. response.status.code = ::cartographer_ros_msgs::StatusCode::OK;
  640. response.trajectory_states.header.stamp = ros::Time::now();
  641. for (const auto& entry : map_builder_bridge_.GetTrajectoryStates()) {
  642. response.trajectory_states.trajectory_id.push_back(entry.first);
  643. switch (entry.second) {
  644. case TrajectoryState::ACTIVE:
  645. response.trajectory_states.trajectory_state.push_back(
  646. ::cartographer_ros_msgs::TrajectoryStates::ACTIVE);
  647. break;
  648. case TrajectoryState::FINISHED:
  649. response.trajectory_states.trajectory_state.push_back(
  650. ::cartographer_ros_msgs::TrajectoryStates::FINISHED);
  651. break;
  652. case TrajectoryState::FROZEN:
  653. response.trajectory_states.trajectory_state.push_back(
  654. ::cartographer_ros_msgs::TrajectoryStates::FROZEN);
  655. break;
  656. case TrajectoryState::DELETED:
  657. response.trajectory_states.trajectory_state.push_back(
  658. ::cartographer_ros_msgs::TrajectoryStates::DELETED);
  659. break;
  660. }
  661. }
  662. return true;
  663. }
  664. bool Node::HandleFinishTrajectory(
  665. ::cartographer_ros_msgs::FinishTrajectory::Request& request,
  666. ::cartographer_ros_msgs::FinishTrajectory::Response& response) {
  667. absl::MutexLock lock(&mutex_);
  668. response.status = FinishTrajectoryUnderLock(request.trajectory_id);
  669. return true;
  670. }
  671. bool Node::HandleWriteState(
  672. ::cartographer_ros_msgs::WriteState::Request& request,
  673. ::cartographer_ros_msgs::WriteState::Response& response) {
  674. absl::MutexLock lock(&mutex_);
  675. if (map_builder_bridge_.SerializeState(request.filename,
  676. request.include_unfinished_submaps)) {
  677. response.status.code = cartographer_ros_msgs::StatusCode::OK;
  678. response.status.message =
  679. absl::StrCat("State written to '", request.filename, "'.");
  680. } else {
  681. response.status.code = cartographer_ros_msgs::StatusCode::INVALID_ARGUMENT;
  682. response.status.message =
  683. absl::StrCat("Failed to write '", request.filename, "'.");
  684. }
  685. return true;
  686. }
  687. bool Node::HandleReadMetrics(
  688. ::cartographer_ros_msgs::ReadMetrics::Request& request,
  689. ::cartographer_ros_msgs::ReadMetrics::Response& response) {
  690. absl::MutexLock lock(&mutex_);
  691. response.timestamp = ros::Time::now();
  692. if (!metrics_registry_) {
  693. response.status.code = cartographer_ros_msgs::StatusCode::UNAVAILABLE;
  694. response.status.message = "Collection of runtime metrics is not activated.";
  695. return true;
  696. }
  697. metrics_registry_->ReadMetrics(&response);
  698. response.status.code = cartographer_ros_msgs::StatusCode::OK;
  699. response.status.message = "Successfully read metrics.";
  700. return true;
  701. }
  702. void Node::FinishAllTrajectories() {
  703. absl::MutexLock lock(&mutex_);
  704. for (const auto& entry : map_builder_bridge_.GetTrajectoryStates()) {
  705. if (entry.second == TrajectoryState::ACTIVE) {
  706. const int trajectory_id = entry.first;
  707. CHECK_EQ(FinishTrajectoryUnderLock(trajectory_id).code,
  708. cartographer_ros_msgs::StatusCode::OK);
  709. }
  710. }
  711. }
  712. bool Node::FinishTrajectory(const int trajectory_id) {
  713. absl::MutexLock lock(&mutex_);
  714. return FinishTrajectoryUnderLock(trajectory_id).code ==
  715. cartographer_ros_msgs::StatusCode::OK;
  716. }
  717. void Node::RunFinalOptimization() {
  718. {
  719. for (const auto& entry : map_builder_bridge_.GetTrajectoryStates()) {
  720. const int trajectory_id = entry.first;
  721. if (entry.second == TrajectoryState::ACTIVE) {
  722. LOG(WARNING)
  723. << "Can't run final optimization if there are one or more active "
  724. "trajectories. Trying to finish trajectory with ID "
  725. << std::to_string(trajectory_id) << " now.";
  726. CHECK(FinishTrajectory(trajectory_id))
  727. << "Failed to finish trajectory with ID "
  728. << std::to_string(trajectory_id) << ".";
  729. }
  730. }
  731. }
  732. // Assuming we are not adding new data anymore, the final optimization
  733. // can be performed without holding the mutex.
  734. map_builder_bridge_.RunFinalOptimization();
  735. }
  736. void Node::HandleOdometryMessage(const int trajectory_id,
  737. const std::string& sensor_id,
  738. const nav_msgs::Odometry::ConstPtr& msg) {
  739. absl::MutexLock lock(&mutex_);
  740. if (!sensor_samplers_.at(trajectory_id).odometry_sampler.Pulse()) {
  741. return;
  742. }
  743. auto sensor_bridge_ptr = map_builder_bridge_.sensor_bridge(trajectory_id);
  744. auto odometry_data_ptr = sensor_bridge_ptr->ToOdometryData(msg);
  745. if (odometry_data_ptr != nullptr) {
  746. extrapolators_.at(trajectory_id).AddOdometryData(*odometry_data_ptr);
  747. }
  748. sensor_bridge_ptr->HandleOdometryMessage(sensor_id, msg);
  749. }
  750. void Node::HandleNavSatFixMessage(const int trajectory_id,
  751. const std::string& sensor_id,
  752. const sensor_msgs::NavSatFix::ConstPtr& msg) {
  753. absl::MutexLock lock(&mutex_);
  754. if (!sensor_samplers_.at(trajectory_id).fixed_frame_pose_sampler.Pulse()) {
  755. return;
  756. }
  757. map_builder_bridge_.sensor_bridge(trajectory_id)
  758. ->HandleNavSatFixMessage(sensor_id, msg);
  759. }
  760. void Node::HandleLandmarkMessage(
  761. const int trajectory_id, const std::string& sensor_id,
  762. const cartographer_ros_msgs::LandmarkList::ConstPtr& msg) {
  763. absl::MutexLock lock(&mutex_);
  764. if (!sensor_samplers_.at(trajectory_id).landmark_sampler.Pulse()) {
  765. return;
  766. }
  767. map_builder_bridge_.sensor_bridge(trajectory_id)
  768. ->HandleLandmarkMessage(sensor_id, msg);
  769. }
  770. void Node::HandleImuMessage(const int trajectory_id,
  771. const std::string& sensor_id,
  772. const sensor_msgs::Imu::ConstPtr& msg) {
  773. absl::MutexLock lock(&mutex_);
  774. if (!sensor_samplers_.at(trajectory_id).imu_sampler.Pulse()) {
  775. return;
  776. }
  777. auto sensor_bridge_ptr = map_builder_bridge_.sensor_bridge(trajectory_id);
  778. auto imu_data_ptr = sensor_bridge_ptr->ToImuData(msg);
  779. if (imu_data_ptr != nullptr) {
  780. extrapolators_.at(trajectory_id).AddImuData(*imu_data_ptr);
  781. }
  782. sensor_bridge_ptr->HandleImuMessage(sensor_id, msg);
  783. }
  784. void Node::HandleLaserScanMessage(const int trajectory_id,
  785. const std::string& sensor_id,
  786. const sensor_msgs::LaserScan::ConstPtr& msg) {
  787. absl::MutexLock lock(&mutex_);
  788. if (!sensor_samplers_.at(trajectory_id).rangefinder_sampler.Pulse()) {
  789. return;
  790. }
  791. map_builder_bridge_.sensor_bridge(trajectory_id)
  792. ->HandleLaserScanMessage(sensor_id, msg);
  793. }
  794. void Node::HandleMultiEchoLaserScanMessage(
  795. const int trajectory_id, const std::string& sensor_id,
  796. const sensor_msgs::MultiEchoLaserScan::ConstPtr& msg) {
  797. absl::MutexLock lock(&mutex_);
  798. if (!sensor_samplers_.at(trajectory_id).rangefinder_sampler.Pulse()) {
  799. return;
  800. }
  801. map_builder_bridge_.sensor_bridge(trajectory_id)
  802. ->HandleMultiEchoLaserScanMessage(sensor_id, msg);
  803. }
  804. void Node::HandlePointCloud2Message(
  805. const int trajectory_id, const std::string& sensor_id,
  806. const sensor_msgs::PointCloud2::ConstPtr& msg) {
  807. absl::MutexLock lock(&mutex_);
  808. if (!sensor_samplers_.at(trajectory_id).rangefinder_sampler.Pulse()) {
  809. return;
  810. }
  811. map_builder_bridge_.sensor_bridge(trajectory_id)
  812. ->HandlePointCloud2Message(sensor_id, msg);
  813. }
  814. void Node::SerializeState(const std::string& filename,
  815. const bool include_unfinished_submaps) {
  816. absl::MutexLock lock(&mutex_);
  817. CHECK(
  818. map_builder_bridge_.SerializeState(filename, include_unfinished_submaps))
  819. << "Could not write state.";
  820. }
  821. void Node::LoadState(const std::string& state_filename,
  822. const bool load_frozen_state) {
  823. absl::MutexLock lock(&mutex_);
  824. map_builder_bridge_.LoadState(state_filename, load_frozen_state);
  825. }
  826. void Node::MaybeWarnAboutTopicMismatch(
  827. const ::ros::WallTimerEvent& unused_timer_event) {
  828. ::ros::master::V_TopicInfo ros_topics;
  829. ::ros::master::getTopics(ros_topics);
  830. std::set<std::string> published_topics;
  831. std::stringstream published_topics_string;
  832. for (const auto& it : ros_topics) {
  833. std::string resolved_topic = node_handle_.resolveName(it.name, false);
  834. published_topics.insert(resolved_topic);
  835. published_topics_string << resolved_topic << ",";
  836. }
  837. bool print_topics = false;
  838. for (const auto& entry : subscribers_) {
  839. int trajectory_id = entry.first;
  840. for (const auto& subscriber : entry.second) {
  841. std::string resolved_topic = node_handle_.resolveName(subscriber.topic);
  842. if (published_topics.count(resolved_topic) == 0) {
  843. LOG(WARNING) << "Expected topic \"" << subscriber.topic
  844. << "\" (trajectory " << trajectory_id << ")"
  845. << " (resolved topic \"" << resolved_topic << "\")"
  846. << " but no publisher is currently active.";
  847. print_topics = true;
  848. }
  849. }
  850. }
  851. if (print_topics) {
  852. LOG(WARNING) << "Currently available topics are: "
  853. << published_topics_string.str();
  854. }
  855. }
  856. } // namespace cartographer_ros

到此就完成了carto_odom的发布,该话题包含了Cartographer的定位信息。

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/96201
推荐阅读
相关标签
  

闽ICP备14008679号