13.客户端Client的编程实现

学习视频:https://www.bilibili.com/video/BV1zt411G7Vn?p=13
目标:通过客户端程序发布请求给spawn服务器创建第二只小海龟
一、创建功能包
打开终端,输入命令

cd ~/catkin_ws/src
catkin_create_pkg learning_service roscpp rospy stdmsgs geometry_msgs turtlesim

二、用C++创建客户端代码
1.创建客户端代码
输入指令,打开turtle_spawn.cpp文件

gedit ~/catkin_ws/src/learning_service/src/turtle_spawn.cpp

复制下列代码,保存退出。

/***********************************************************************
Copyright 2020 GuYueHome (www.guyuehome.com).
***********************************************************************/

/**
 * 该例程将请求/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<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;
};

2.配置客户端代码编译规制
输入指令,打开CMakeList.txr文件

gedit ~/catkin_ws/src/learning_service/CMakeLists.txt

加入下面代码如下图所示

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

13.客户端Client的编程实现_第1张图片
三、用Pyhton创建客户端代码
1.创建客户端代码
输入指令,打开turtle_spawn.py文件。

mkdir ~/catkin_ws/src/learning_service/scripts
gedit ~/catkin_ws/src/learning_service/scripts/turtle_spawn.py

复制下列代码,保存关闭文件。

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

########################################################################
####          Copyright 2020 GuYueHome (www.guyuehome.com).          ###
########################################################################

# 该例程将请求/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()))

这里Python3和Python2语法不相同,我作了一些修改。
2.设置turtle_spawn.py 文件运行权限

cd ~/catkin_ws/src/learning_service/scripts
chmod +x turtle_spawn.py 

四、编译功能包(Python不需要)

cd ~/catkin_ws/
catkin_make

五、运行程序
1.运行roscore

roscore

2.打开新的终端,运行小海龟仿真器

rosrun turtlesim turtlesim_node 

3.打开新的终端,运行指令

rosrun learning_service turtle_spawn.py

4.运行效果如下
13.客户端Client的编程实现_第2张图片

你可能感兴趣的:(古月ROS入门21讲)