这里记录下使用ROS中的服务生成turtlesim小乌龟。
要实现这个内容,需要先确定生成乌龟的服务是什么,然后才能用编程实现。
使用ROS命令查看服务
rosservice list
通过上面的内容,可以发现,支持乌龟生成的是 spawn 这个服务,确定了服务,下面的就是关注服务的信息数据是什么。通过下面的命令实现
rosservice type /spawn
查看服务数据类型
rossrv info turtlesim/Spawn
C++实现
#include "ros/ros.h"
#include "turtlesim/Spawn.h"
int main(int argc,char *argv[]){
ros::init(argc,argv,"test_03_service_client");
ros::NodeHandle nh;
ros::ServiceClient sc = nh.serviceClient<turtlesim::Spawn>("/spawn");
//组织信息对象
//1. 请求数据设置
turtlesim::Spawn spawn;
spawn .request.x = 1.0;
spawn.request.y=4.0;
spawn.request.theta=1.5;
//不能重复调用,否则会报错
spawn.request.name="turtle2";
//2. 发送请求
//判断服务器状态
sc.waitForExistence();
//ros::service::waitForService("spawn");
bool flag = sc.call(spawn);
if(flag){
ROS_INFO("new gui appear .. the name %s",spawn.response.name.c_str());
}else{
ROS_INFO("new gui disappear...");
}
ros::spin();
return 0;
}
Python 实现
#! /usr/bin/env python
# -*- coding:utf-8 -*-
import rospy
from turtlesim.srv import Spawn,SpawnRequest,SpawnResponse
if __name__=="__main__":
rospy.init_node("test_03_client_p")
#创建client 对象
client = rospy.ServiceProxy("/spawn",Spawn)
#组织消息对象
request = SpawnRequest()
request.x = 1.0
request.y = 4.0
request.theta = 1.5
#不能重复调用
request.name = "turtle3"
#判断服务器的状态
client.wait_for_service()
try:
#发送数据
response = client.call(request)
#打印参数
rospy.loginfo("the service name :%s",response.name)
except Exception as e:
rospy.logerr("wrong response...")
【注:要注意配置CMakeLists.txt,编译后运行】