ROS-客户端Client的编程实现(八)

1、把之前的learning_topic移到桌面或其他地方

2、创建功能包

cd /catkin_ws/src
catkin_create_pkg learning_service roscpp rospy std_msgs geometry_msgs turtlesim
 

然后在你创建的learning_service 文件下的src文件下创建一个turtle_spawn.cpp文件

touch turtle_spawn.cpp

3.创建C++文件

在.cpp文件下输入

/**
 * 该例程将请求/spawn服务,服务数据类型turtlesim::Spawn
 */

#include 
#include 

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("/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;
};

如何实现一个客户端

  • 初始化ROS结点
  • 创建一个Client实例;
  • 发布服务请求数据;
  • 等待Server处理之后的应答结果

3.编辑CMakeLists.txt

加上这两句

add_executable(turtle_spawn src/turtle_spawn.cpp)
target_link_libraries(turtle_spawn ${catkin_LIBRARIES})

ROS-客户端Client的编程实现(八)_第1张图片

/////////////////////////////////////////////////////

1、创建功能包
进入工作空间catkin_ws/src下面打开功能包

chen@ubuntu:~/catkin_ws/src$ catkin_create_pkg learning_service roscpp rospy std_msgs geometry_msgs turtlesim
usage: catkin_create_pkg [-h] [--meta] [-s [SYS_DEPS [SYS_DEPS ...]]]
                         [-b [BOOST_COMPS [BOOST_COMPS ...]]] [-V PKG_VERSION]
                         [-D DESCRIPTION] [-l LICENSE] [-a AUTHOR]
                         [-m MAINTAINER] [--rosdistro ROSDISTRO]
                         name [dependencies [dependencies ...]]
catkin_create_pkg: error: File exists: /home/chen/catkin_ws/src/learning_service/package.xml

运行roscore

运行客户端节点

rosrun learning_service turtle_spawn

ROS-客户端Client的编程实现(八)_第2张图片

 

ROS-客户端Client的编程实现(八)_第3张图片

 

 

你可能感兴趣的:(ROS-客户端Client的编程实现(八))