目录
一、服务名称与消息的获取
rosservice list
rosservice type /spawn
rossrv info turtlesim/Spawn
二、代码案例
1、C++
//包含头文件
#include "ros/ros.h"
#include "turtlesim/Spawn.h"
int main(int argc, char *argv[])
{
//初始化 ros 节点
ros::init(argc,argv,"set_turtle");
//创建 ros 句柄
ros::NodeHandle nh;
//创建 service 客户端
ros::ServiceClient client = nh.serviceClient<turtlesim::Spawn>("/spawn");
//等待服务启动
ros::service::waitForService("/spawn");
//发送请求
turtlesim::Spawn spawn;
spawn.request.x = 1.0;
spawn.request.y = 1.0;
spawn.request.theta = 1.57;
spawn.request.name = "my_turtle";
bool flag = client.call(spawn);
if (flag)
{
ROS_INFO("%s",spawn.response.name.c_str());
} else {
ROS_INFO("error");
}
return 0;
}
2、python
#! /usr/bin/env python
# -*- coding:UTF-8 -*-
#导包
import rospy
from turtlesim.srv import Spawn,SpawnRequest,SpawnResponse
if __name__ == "__main__":
#初始化 ros 节点
rospy.init_node("set_turtle_p")
#创建 service 客户端
client = rospy.ServiceProxy("/spawn",Spawn)
# 4.等待服务启动
client.wait_for_service()
# 5.发送请求
req = SpawnRequest()
req.x = 2.0
req.y = 2.0
req.theta = -1.57
req.name = "my_turtle_p"
try:
response = client.call(req)
# 6.处理响应
rospy.loginfo("%s",response.name)
except Exception as identifier:
rospy.loginfo("error")
三、编译运行
1、配置cmakelist