自定义服务数据类型
1 自定义服务数据
在包下创建srv文件夹,在该文件夹下:
创建文件:custom_srv.srv
uint8 x
uint8 y
---
uint8 result
配置方式与配置msg文件相同,即:
在package文件中添加依赖:
# 编译依赖
<build_depend>message_generation</build_depend>
# 执行依赖
<exec_depend>message_runtime</exec_depend>
在CMakeList文件中添加编译选项:
配置好后编译;在工作空间/devel/include/包名/ 下会生成三个头文件
2 c++
目的:编写一个服务用于两个数相加
2.1 服务端
创建文件:custom_server.cpp
#include <ros/ros.h>
#include <service_pkg/custom_srv.h>
bool CallBack(service_pkg::custom_srv::Request& req,
service_pkg::custom_srv::Response& res)
{
ROS_INFO("-----------");
res.result = req.x + req.y;
ROS_INFO("result:%d",res.result);
return true;
}
int main(int argc,char** argv){
ros::init(argc,argv,"custom_server");
ros::NodeHandle n;
ros::ServiceServer ser = n.advertiseService("/server_temp",CallBack);
ros::spin();
return 0;
}
配置:
add_executable(custom_server src/custom_server.cpp)
target_link_libraries(custom_server ${catkin_LIBRARIES})
运行:
rosrun service_pkg custom_server
rosservice call /server_temp 双击tab键
2.2 客户端
创建文件:custom_client.cpp
#include <ros/ros.h>
#include <service_pkg/custom_srv.h>
int main(int argc,char** argv){
ros::init(argc,argv,"custom_client");
ros::NodeHandle n;
ros::service::waitForService("/server_temp");
ros::ServiceClient cli = n.serviceClient<service_pkg::custom_srv>("/server_temp",10);
service_pkg::custom_srv srv;
srv.request.x = 10;
srv.request.y = 45;
ROS_INFO("request:x:%d,y:%d", srv.request.x, srv.request.y);
cli.call(srv);
return 0;
}
配置完成后并运行:
3 python
实现的任务和c++一样
3.1 服务端
创建文件:custom_server.py
#!/usr/bin/env python
import rospy
from service_pkg.srv import custom_srv, custom_srvResponse
def CallBack(res):
rospy.loginfo("------------------")
rospy.loginfo(res.x+res.y)
return custom_srvResponse(res.x+res.y)
def custom_server():
rospy.init_node("custom_server")
s = rospy.Service("/server_cus_py",custom_srv,CallBack)
rospy.loginfo("-----ready-----")
rospy.spin()
if __name__ == "__main__":
custom_server()
将文件改为可执行文件
rosrun service_pkg custom_server.py
rosservice call /server_cus_py 双击tab键
3.2 客户端
创建文件:custom_client.py
#!/usr/bin/env python
import rospy
from service_pkg.srv import custom_srv
def custom_client():
try:
rospy.init_node("custom_client")
rospy.wait_for_service("/server_cus_py")
cli = rospy.ServiceProxy("/server_cus_py",custom_srv)
# 发出请求
rospy.loginfo("-------request---------")
res = cli(34,45)
except rospy.ServiceException as e:
rospy.loginfo(e)
if __name__ == "__main__":
custom_client()
运行: