本文主要是介绍第十二弹 服务器Server的编程实现,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.服务模型(客户端/服务器)
2.创建服务器
新建一个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,输出res
bool 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_comand_server");//创建节点句柄ros::NodeHandle n;//ros::NodeHandle node;//创建一个名为/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;
}
3. 配置服务器代码编译规则
- 设置需要编译的代码和生成的可执行文件
- 设置链接库
add_executable(turtle_command_server src/turtle_command_server.cpp)
target_link_libraries(turtle_command_server ${catkin_LIBRARIES} )
4. 编译和运行
在~/catkin_ws的目录下,运行catkin_make指令进行编译。
运行:
roscorerosrun turtlesim turtlesim_node rosrun learning_service turtle_command_server
再打开一个终端,发送请求:
rosservice call /turtle_command "{}"
这篇关于第十二弹 服务器Server的编程实现的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!