add_octomap.cpp 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #include <ros/ros.h>
  2. #include <moveit/move_group_interface/move_group_interface.h>
  3. #include <moveit/planning_scene_interface/planning_scene_interface.h>
  4. #include <octomap_msgs/Octomap.h>
  5. #include <octomap_msgs/conversions.h>
  6. #include <octomap/OcTree.h>
  7. void appendScene(const std::string& octoFile)
  8. {
  9. ros::NodeHandle nh("~");
  10. // 创建 MoveIt MoveGroup Interface
  11. moveit::planning_interface::MoveGroupInterface group("manipulator");
  12. std::string frameId = group.getPlanningFrame();
  13. // 从文件加载 OctoMap
  14. octomap::OcTree* octree = new octomap::OcTree(octoFile);
  15. // 将 Octomap 数据转换为 ROS 消息
  16. octomap_msgs::Octomap octomap_msg;
  17. if (!octomap_msgs::fullMapToMsg(*octree, octomap_msg))
  18. {
  19. ROS_ERROR("Failed to convert Octomap to ROS message.");
  20. return;
  21. }
  22. // 创建 PlanningSceneInterface 实例
  23. moveit::planning_interface::PlanningSceneInterface psi;
  24. // 创建 PlanningScene 消息
  25. moveit_msgs::PlanningScene planning_scene_msg;
  26. planning_scene_msg.is_diff = true;
  27. // 设置 Octomap 的相关信息
  28. planning_scene_msg.world.octomap.header.frame_id = "base_link";
  29. planning_scene_msg.world.octomap.octomap = octomap_msg;
  30. // 设置Octomap的原点位置
  31. // planning_scene_msg.world.octomap.origin.position.x = 0.0;
  32. // planning_scene_msg.world.octomap.origin.position.y = 0.0;
  33. // planning_scene_msg.world.octomap.origin.position.z = 0.0;
  34. // // 设置有效的四元数
  35. // planning_scene_msg.world.octomap.origin.orientation.x = 0.0;
  36. // planning_scene_msg.world.octomap.origin.orientation.y = 0.0;
  37. // planning_scene_msg.world.octomap.origin.orientation.z = 0.0;
  38. // planning_scene_msg.world.octomap.origin.orientation.w = 1.0;
  39. planning_scene_msg.world.octomap.header.stamp = ros::Time::now();
  40. // 将 PlanningScene 消息应用到 MoveIt 中
  41. psi.applyPlanningScene(planning_scene_msg);
  42. delete octree; // 释放内存
  43. }
  44. int main(int argc, char **argv)
  45. {
  46. ros::init(argc, argv, "append_scene_node");
  47. ros::NodeHandle nh;
  48. // 检查是否传入了OctoMap文件名参数
  49. if (argc < 2)
  50. {
  51. ROS_ERROR("Usage: %s [octomap_file]", argv[0]);
  52. return 1;
  53. }
  54. std::string octoFile = argv[1];
  55. appendScene(octoFile);
  56. // 确保所有更改都已发送给MoveIt!
  57. ros::Duration(1.0).sleep(); // 等待一段时间以确保消息被处理
  58. ROS_INFO("Planning scene updated with OctoMap.");
  59. return 0;
  60. }