定义Client
Client客户端发请求,要求turtle做
//等待turtle的节点开启, rostopic里面产生"/spawn"话题
ros::service::waitForService("/spawn");
//定义一个客户端服务(ServiceClient 客户端+服务) :add_turtle
ros::ServiceClient add_turtle
//ros句柄 调用serviceClient;类型是turtlesim::Spawn;话题是:"/spawn"
add_turtle=n.serviceClient<turtlesim::Spawn>("/spawn");
消息类型名:turtlesim::Spawn 变量名:srv
turtlesim::Spawn srv;
srv.request.x=2.0;
srv.request.y=2.0;
srv.request.name="turtle2";
//用定义的客户端服务传递srv消息给(客户端服务的)"/spawn"
add_turtle.call(srv);
定义Client
Server服务器,接收命令
//定义一个服务器服务ServiceServer(服务器+服务)
ros::ServiceServer command_service;
//调用ros句柄,服务器的节点名:"/turtle_command"(应与初始化的一致),回调函数名:callback
command_service=n.advertiseService("/turtle_command",callback);
//阻塞进程一次,回调一次就放行,放在while里面
ros::spinOnce();
//回调函数
//触发类型的消息std_srvs::Trigger::Request,std_srvs::Trigger::Response
bool callback(std_srvs::Trigger::Request &req,std_srvs::Trigger::Response &res){
//是不是触发成功
res.success=true;
res.message="change turtle command state!";
return true;
}
标签:turtle,spawn,Server,Client,srv,command,ros,客户端
From: https://www.cnblogs.com/blogofzcfu/p/18637855