服务编程流程:
创建服务器创建客户端添加编译选项运行可执行程序
实现客户端Clien
创建功能包
cd ~/catkin_ws/src
catkin_create_pkg learning_service roscpp rospy std_msgs geometry_msgs turtlesim
如何实现一个客户端
初始化ROS节点创建一个Client实例发布服务请求数据等待Server处理之后的应答结果
在刚创建的 learning_service 目录中的src文件夹下创建一个 cpp文件
cd ~/catkin_ws/src/learning_service/src
touch turtle_spawn.cpp
在 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的serviceros::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;};
在CMakeLists.txt中添加以下代码:
add_executable(turtle_spawn src/turtle_spawn.cpp)target_link_libraries(turtle_spawn ${catkin_LIBRARIES})
编译项目
cd ~/catkin_ws
catkin_make
设置环境变量,让系统能够找到该工作空间
source devel/setup.bash
启动ROS Master
roscore
启动小海龟仿真器
rosrun turtlesim turtlesim_node
启动自定义的海龟控制节点,会在客户端中生成一个新的小海龟。
rosrun learning_service turtle_spawn
用Python创建客户端步骤:
cd ~/catkin_ws/src/learning_service
创建 scripts 文件夹
mkdir scripts
cd scripts
创建 turtle_spawn.py Python文件
touch turtle_spawn.py
用Python创建客户端代码:
下面代码实现功能: 请求/spawn服务,服务数据类型turtlesim::Spawn
import sysimport rospyfrom turtlesim.srv import Spawndef turtle_spawn():# ROS节点初始化rospy.init_node('turtle_spawn')# 发现/spawn服务后,创建一个服务客户端,连接名为/spawn的servicerospy.wait_for_service('/spawn')try:add_turtle = rospy.ServiceProxy('/spawn', Spawn)# 请求服务调用,输入请求数据response = add_turtle(2.0, 2.0, 0.0, "turtle2")return response.nameexcept rospy.ServiceException, e:print "Service call failed: %s"%eif __name__ == "__main__":#服务调用并显示调用结果print "Spwan turtle successfully [name:%s]" %(turtle_spawn())
Python代码不需要重新编译,可以直接执行。
rosrun learning_service turtle_spawn.py
实现服务端Server
如何实现一个服务器
初始化ROS节点创建Server实例循环等待服务请求,进入回调函数在回调函数中完成服务功能的处理,并反馈应答数据。
在创建的 learning_service 目录中的src文件夹下创建一个 turtle_command_server.cpp文件
cd ~/catkin_ws/src/learning_service/src
touch turtle_command_server.cpp
在 turtle_command_server.cpp 文件中写入以下代码。
下面代码实现功能:执行/turtle_command服务,服务数据类型std_srvs/Trigger
#include <ros/ros.h>#include <geometry_msgs/Twist.h>#include <std_srvs/Trigger.h>ros::Publisher turtle_vel_pub;bool pubCommand = false;// service回调函数,输入参数req,输出参数resbool commandCallback(std_srvs::Trigger::Request &req,std_srvs::Trigger::Response &res){pubCommand = !pubCommand;// 显示请求数据ROS_INFO("Publish turtle velocity command [%s]", pubCommand==true?"Yes":"No");// 设置反馈数据res.success = true;res.message = "Change turtle command state!";return true;}int main(int argc, char **argv){// ROS节点初始化ros::init(argc, argv, "turtle_command_server");// 创建节点句柄ros::NodeHandle n;// 创建一个名为/turtle_command的server,注册回调函数commandCallbackros::ServiceServer command_service = n.advertiseService("/turtle_command", commandCallback);// 创建一个Publisher,发布名为/turtle1/cmd_vel的topic,消息类型为geometry_msgs::Twist,队列长度10turtle_vel_pub = n.advertise<geometry_msgs::Twist>("/turtle1/cmd_vel", 10);// 循环等待回调函数ROS_INFO("Ready to receive turtle command.");// 设置循环的频率ros::Rate loop_rate(10);while(ros::ok()){// 查看一次回调函数队列ros::spinOnce();// 如果标志为true,则发布速度指令if(pubCommand){geometry_msgs::Twist vel_msg;vel_msg.linear.x = 0.5;vel_msg.angular.z = 0.2;turtle_vel_pub.publish(vel_msg);}//按照循环频率延时loop_rate.sleep();}return 0;}
注:
可以通过以下指令 显示服务类型的所有信息
rossrv show 头文件名
例如:
rossrv show std_srvs/Trigger
在CMakeLists.txt中添加以下代码:
add_executable(turtle_command_server src/turtle_command_server.cpp)target_link_libraries(turtle_command_server ${catkin_LIBRARIES})
编译项目
cd ~/catkin_ws
catkin_make
设置环境变量,让系统能够找到该工作空间
source devel/setup.bash
启动ROS Master
roscore
启动小海龟仿真器
rosrun turtlesim turtlesim_node
启动自定义的海龟控制节点,会在客户端中生成一个新的小海龟。
rosrun learning_service turtle_command_server
以下指令相当于海龟的开关,发送一次,海龟就会启动,再次发送时,就会让海龟停止运动。
rosservice call /turtle_command "{}"
用Python创建服务端步骤:
cd ~/catkin_ws/src/learning_service
创建 scripts 文件夹
mkdir scripts
cd scripts
创建 turtle_command_server.py Python文件
touch turtle_command_server.py
用Python创建客户端代码:
下面代码实现功能: 执行/turtle_command服务,服务数据类型std_srvs/Trigger
import rospyimport thread,timefrom geometry_msgs.msg import Twistfrom std_srvs.srv import Trigger, TriggerResponsepubCommand = False;turtle_vel_pub = rospy.Publisher('/turtle1/cmd_vel', Twist, queue_size=10)def command_thread():while True:if pubCommand:vel_msg = Twist()vel_msg.linear.x = 0.5vel_msg.angular.z = 0.2turtle_vel_pub.publish(vel_msg)time.sleep(0.1)def commandCallback(req):global pubCommandpubCommand = bool(1-pubCommand)# 显示请求数据rospy.loginfo("Publish turtle velocity command![%d]", pubCommand)# 反馈数据return TriggerResponse(1, "Change turtle command state!")def turtle_command_server():# ROS节点初始化rospy.init_node('turtle_command_server')# 创建一个名为/turtle_command的server,注册回调函数commandCallbacks = rospy.Service('/turtle_command', Trigger, commandCallback)# 循环等待回调函数print "Ready to receive turtle command."thread.start_new_thread(command_thread, ())rospy.spin()if __name__ == "__main__":turtle_command_server()
启动ROS Master
roscore
启动小海龟仿真器
rosrun turtlesim turtlesim_node
Python代码不需要重新编译,可以直接执行。
rosrun learning_service turtle_command_server.py
以下指令相当于海龟的开关,发送一次,海龟就会启动,再次发送时,就会让海龟停止运动。
rosservice call /turtle_command "{}"