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
其中的横线是三个短横线,上面是客户端发给服务端的消息类型,下面是服务端发给客户端的
- 在package.xml加
<build_depend>message_generation</build_depend>
<exec_depend>message_runtime</exec_depend>
- 修改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"
#include <cstdlib>
int 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<msg_srv::AddTwoInts>("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
版权声明:本文为random_repick原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。