成都网站建设设计

将想法与焦点和您一起共享

ros使用service的所有步骤-创新互联

1.生成头文件
  • catkin_create_pkg msg_srv roscpp std_msgs
  • cd msg_srv/
  • mkdir srv
  • roscp rospy_tutorials AddTwoInts.srv srv/AddTwoInts.srv

为了省事复制了一个,内容是:
int64 a
int64 b

int64 sum
其中的横线是三个短横线,上面是客户端发给服务端的消息类型,下面是服务端发给客户端的

我们提供的服务有:网站制作、成都网站建设、微信公众号开发、网站优化、网站认证、荷塘ssl等。为近1000家企事业单位解决了网站和推广的问题。提供周到的售前咨询和贴心的售后服务,是有科学管理、有技术的荷塘网站制作公司
  • 在package.xml加
message_generationmessage_runtime
  • 修改CMakeLists.txt的若干行
find_package(catkin REQUIRED COMPONENTS roscpp rospy std_msgs message_generation)
catkin_package(
  ...
  CATKIN_DEPENDS message_runtime ...
  ...
)
add_service_files(
  FILES
  AddTwoInts.srv
)
generate_messages(
  DEPENDENCIES
  std_msgs
)
  • cd …/…
  • catkin_make --pkg msg_srv
  • 生成的C++头文件将会放置在~/catkin_ws/devel/include/msg_srv/
2.服务端和客户端
  • add_two_ints_server.cpp
#include "ros/ros.h"
#include "msg_srv/AddTwoInts.h"

bool add(msg_srv::AddTwoInts::Request  &req,
         msg_srv::AddTwoInts::Response &res)
{res.sum = req.a + req.b;
  ROS_INFO("request: x=%ld, y=%ld", (long int)req.a, (long int)req.b);
  ROS_INFO("sending back response: [%ld]", (long int)res.sum);
  return true;
}

int main(int argc, char **argv)
{ros::init(argc, argv, "add_two_ints_server");
  ros::NodeHandle n;

  ros::ServiceServer service = n.advertiseService("add_two_ints", add);
  ROS_INFO("Ready to add two ints.");
  ros::spin();

  return 0;
}
  • add_two_ints_client.cpp
#include "ros/ros.h"
#include "msg_srv/AddTwoInts.h"
#includeint main(int argc, char **argv)
{ros::init(argc, argv, "add_two_ints_client");
  if (argc != 3)
  {ROS_INFO("usage: add_two_ints_client X Y");
    return 1;
  }

  ros::NodeHandle n;
  ros::ServiceClient client = n.serviceClient("add_two_ints");
  msg_srv::AddTwoInts srv;
  srv.request.a = atoll(argv[1]);
  srv.request.b = atoll(argv[2]);
  if (client.call(srv))
  {ROS_INFO("Sum: %ld", (long int)srv.response.sum);
  }
  else
  {ROS_ERROR("Failed to call service add_two_ints");
    return 1;
  }

  return 0;
}
  • CMakeLists.txt合适位置添加
add_executable(add_two_ints_server src/add_two_ints_server.cpp)
target_link_libraries(add_two_ints_server ${catkin_LIBRARIES})
add_dependencies(add_two_ints_server msg_srv_gencpp)

add_executable(add_two_ints_client src/add_two_ints_client.cpp)
target_link_libraries(add_two_ints_client ${catkin_LIBRARIES})
add_dependencies(add_two_ints_client msg_srv_gencpp)
  • 编译成功后,使用以下命令执行
rosrun msg_srv add_two_ints_server
rosrun msg_srv add_two_ints_client 1 39

你是否还在寻找稳定的海外服务器提供商?创新互联www.cdcxhl.cn海外机房具备T级流量清洗系统配攻击溯源,准确流量调度确保服务器高可用性,企业级服务器适合批量采购,新人活动首月15元起,快前往官网查看详情吧


当前标题:ros使用service的所有步骤-创新互联
当前链接:http://chengdu.cdxwcx.cn/article/dicsid.html