申明:ROS学习参考了古月居老师的Blibli视频,强烈推荐大家看视频学习,本博客仅记录自己的学习经历和心得,欢迎大家一起讨论!
本节,首先定义一个服务模型。其中,ROS Master是节点管理器,其下有两个主要节点,Client是客户端节点turtle_spawn(本节的主要工作),Server是服务端节点turtlesim(小海龟仿真器)。Client发送请求Request给Server,Server接收到请求后给出应答信息Response,服务Service的名字是/spawn,消息结构是turtlesim::Spawn。
如何创建一个客户端?
#进入src文件
cd ~/catkin_ws/src/
#创建功能包并添加依赖
catkin_create_pkg learning_service roscpp rospy std_msgs geometry_msgs turtlesim
在learning_service下的src文件夹下新建.cpp文件或.py文件,需要在此learning_service/src文件夹下运行:
(1)创建C++文件
touch turtle_spawn.cpp
(2)编写.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");
//给spawn服务器发送请求,请求的数据类型是turtlesim::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);
//使用call方法发送封装好的请求数据
// 显示服务调用结果
ROS_INFO("Spwan turtle successfully [name:%s]", srv.response.name.c_str());
return 0;
};
(3)配置CMakeLists.txt编译规则
add_executable(turtle_spawn src/turtle_spawn.cpp)#将程序文件生成可执行文件
target_link_libraries(turtle_spawn ${
catkin_LIBRARIES})#将可执行文件与ros库链接
(4)进入catkin_ws 进行可执行文件 turtle_spawn的编译,运行
cd ~/catkin_ws
catkin_make#编译
(5) 程序测试
roscore
rosrun turtlesim turtlesim_node
rosrun learning_service turtle_spawn
(1) 创建.py文件
touch turtle_spawn.py
(2)编写.py文件内容
#!/usr/bin/env python
# -*- 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, e:
print "Service call failed: %s"%e
if __name__ == "__main__":
#服务调用并显示调用结果
print "Spwan turtle successfully [name:%s]" %(turtle_spawn())
pytion开头注释参考
(3) 给文件授权
PS:在ros下运行python文件一定要注意待执行的python文件有可执行权限。对着python文件右键→属性(Properties)→权限(Permissions)→Allow executing file as program打钩。
或者通过命令行修改:(进入learining_service/src/文件夹中)
chmod +x turtle_spawn.py
(4) 程序运行
roscore
rosrun turtlesim turtlesim_node
rosrun learning_service turtle_spawn.py
本讲完,考试结束了,接下来会持续更新!