目录
一、服务名称与消息的获取
二、代码案例
1、C++
2、python
三、编译运行
1、配置cmakelist
2、运行
一、服务名称与消息的获取
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,SpawnResponseif __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.0req.y = 2.0req.theta = -1.57req.name = "my_turtle_p"try:response = client.call(req)# 6.处理响应rospy.loginfo("%s",response.name)except Exception as identifier:rospy.loginfo("error")
三、编译运行
1、配置cmakelist