在上图所示的模型中,Client作为请求的发送端,Server端接收Client发送的指令,并且完成topic指令的发送。其中请求的信息类型是std_srvs::Trigger类,同时返回一个Response,说明是否成功。
服务器端代码实现。
#include<ros/ros.h>
#include<geometry_msgs/Twist.h>
#include<std_srvs/Trigger.h>
//will be used later when publish a topic
ros::Publisher turtle_vel_pub;
//as a flag to show if the turtle is moving or not
bool pubCommand = false;
//service callback function
bool commandCallback(std_srvs::Trigger::Request &req, std_srvs::Trigger::Response &res)
{
pubCommand = !pubCommand;
//display the request data
ROS_INFO("Publish turtle velocity command [%s]", pubCommand==true?"Yes":"No");
//set the callback data
res.success = true;
res.message = "Change turtle command state!";
return true;
}
int main(int argc, char **argv)
{
//initiate ros node
ros::init(argc, argv, "turtle_command_server");
//create node handle
ros::NodeHandle n;
//create a server named /turtle_command, register the command callback function
ros::ServiceServer command_service = n.advertiseService("/turtle_command", commandCallback);
//create a Publisher, publish a topic named /turtle1/cmd_vel, message type is geometry_msgs::Twist, queue length is 10
turtle_vel_pub = n.advertise<geometry_msgs::Twist>("/turtle1/cmd_vel", 10);
ROS_INFO("Ready to receive turtle command.");
//set the frequency of loop
ros::Rate loop_rate(10);
while(ros::ok())
{
//look at queue of callback function once
ros::spinOnce();
//if the flag is true, publish the velosity command
if(pubCommand)
{
geometry_msgs::Twist vel_msg;
vel_msg.linear.x = 0.5;
vel_msgs.angular.z = 0.2;
turtle_vel_pub.publish(vel_msg);
}
//delay by setting
loop_rate.sleep();
}
return 0;
}
修改CMakeList.txt,添加编译规则。
add_executable(turtle_command_server src/turtle_command_server.cpp)
target_link_libraries(turtle_command_server ${catkin_LIBRARIES})
返回catkin_ws目录下进行编译。之后启动海龟仿真节点和服务器节点
rosrun turtlesim turtlesim_node
rosrun learning_service turtle_command_server
rosservice call /turtle_command "{}"
rosservice call来发送/turtle_command请求,每次请求都改变当前的运动状态。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)