一、目的
通过程序,发布服务请求。
即通过客户端的请求,发给服务端产生一个海龟,反馈回客户端。
二、创建功能包
回到catkin_ws/src
文件夹下,创建一个名为learning_service
的功能包
1 2
| cd ~/catkin_ws/src catkin_create_pkg learning_service roscpp rospy std_msgs geometry_msgs turtlesim
|
三、创建客户端代码
在~/catkin_ws/src/learning_service/src
目录下创建一个turtle_spawn.cpp
的文件,其内容为:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
#include <ros/ros.h> #include <turtlesim/Spawn.h>
int main(int argc, char** argv) { ros::init(argc, argv, "turtle_spawn");
ros::NodeHandle node;
ros::service::waitForService("/spawn"); ros::ServiceClient add_turtle = node.serviceClient<turtlesim::Spawn>("/spawn");
turtlesim::Spawn srv; srv.request.x = 2.0; srv.request.y = 2.0; srv.request.name = "turtle2";
ROS_INFO("Call service to spawn turtle[x:%0.6f, y:%0.6f, name:%s]", srv.request.x, srv.request.y, srv.request.name.c_str());
add_turtle.call(srv);
ROS_INFO("Spawn turtle successfully [name:%s]", srv.response.name.c_str());
return 0; };
|
代码👆的实现过程如下:
- 初始化ROS节点
- 创建一个Client实例
- 发布服务请求数据
- 等待Server处理之后的应答结果
四、配置客户端代码编译规则
打开learning_service
中的CMakeLists.txt
,在图示区域添加代码
1 2
| add_executable(turtle_spawn src/turtle_spawn.cpp) target_link_libraries(turtle_spawn ${catkin_LIBRARIES})
|
add_executable添加编译规则,target_link_libraries链接一些需要的库
五、编译与运行
进行编译
1 2
| cd ~/catkin_ws catkin_make
|
运行客户端,可以看到产生了第二个小海龟
1 2 3 4
| source devel/setup.bash roscore rosrun turtlesim turtlesim_node rosrun learning_service turtle_spawn
|
【ROS学习笔记】(六)客户端Client的编程实现