Getting Started with ROS - Implementation of Client Client
service model
Server side: the program of the little turtle
Service:Spawn
Client: the node we are about to release
Client code implementation
Here we create a function package separately:
cd ~/catkin_ws/src
catkin_create_pkg learning_service roscpp rospy std_msgs geometry_msgs turtlesim
How to implement a client:
-
Initialize the ROS node
-
Publish a Client instance
-
Publish service request data
-
Wait for the response result after Server processing
Click to view the full code:
turtle_spawn.cpp
/**
* 该例程将请求 /spawn服务,服务数据类型 turtlesim::Spawn
*/
#include <ros/ros.h>
#include <turtlesim/Spawn.h>
int main(int argc, char** argv)
{
// 初始化ROS节点
ros::init(argc, argv, "turtle_spawn");
// 创建节点句柄
ros::NodeHandle node;
// 发现/spawn服务后,创建一个服务客户端,连接名为/spawn的service
ros::service::waitForService("/spawn");
ros::ServiceClient add_turtle = node.serviceClient<turtlesim::Spawn>("/spawn");
// 初始化turtlesim::Spawn的请求数据
turtlesim::Spawn srv;
srv.request.x = 2.0;
srv.request.y = 2.0;
srv.request.name = "turtle2";
// 请求服务调用
ROS_INFO("Call service to spwan 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("Spwan turtle successfully [name:%s]", srv.response.name.c_str());
return 0;
};
turtle_spawn.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 该例程将请求/spawn服务,服务数据类型turtlesim::Spawn
import sys
import rospy
from turtlesim.srv import Spawn
def turtle_spawn():
# ROS节点初始化
rospy.init_node('turtle_spawn')
# 发现/spawn服务后,创建一个服务客户端,连接名为/spawn的service
rospy.wait_for_service('/spawn')
try:
add_turtle = rospy.ServiceProxy('/spawn', Spawn)
# 请求服务调用,输入请求数据
response = add_turtle(2.0, 2.0, 0.0, "turtle2")
return response.name
except rospy.ServiceException as e:
print("Service call failed: %s"%e)
if __name__ == "__main__":
#服务调用并显示调用结果
print("Spwan turtle successfully [name:%s]" %(turtle_spawn()))
In the past, we all issued commands on the terminal to issue requests. Here we use codes to issue requests. Here we use blocking APIs and wait until the service of spawn is found before proceeding to the next step.
We use the call function when requesting services, which is also a blocking function, and we can only proceed to the next step after waiting for the server to give feedback
The compilation rules here are exactly the same as those we used earlier:
# 在 cMakeLists.txt 中添加如下内容:
add_executable(turtle_spawn src/turtle_spawn.cpp)
target_link_Libraries(turtle_spawn ${catkin_LIBRARIES})
Next, we can directly compile and publish:
run test
# 启动 ROS-Master
roscore
# 在第二个终端运行 turtlesim
rosrun turtlesim turtlesim_node
# 在第三个终端运行刚刚发布的节点
rosrun learning_service turtle_spawn
If you see this effect, it means that our program is fine:
Here you can see that the command line shows that we have generated a new little turtle, and shows the position coordinates of the new turtle