ROS中自定義複雜資料型別
阿新 • • 發佈:2021-01-15
ROS中自定義複雜資料型別
先說一下需求,想要服務的請求資料為一個point(x,y,z)的陣列。具體的形式表示如:
[point1,point2,...]
geometry_msgs::Point
首先是對ROS官方提供的資料型別geometry::Point的認識和理解:
可以看到該資料型別格式如上圖。
所以我們想是不是定義一個Point的陣列就可以了。
自定義新的資料型別gm_ros_package::Points
來看一下自定義的資料型別的格式:
實現對geometry_msgs::Point 的一種封裝。
在程式碼中定義:
gm_ros_package:: Points points;
//points 就是geometry_msgs::Point的陣列
//在賦值時許格外注意,使用vector進行賦值
自定義服務訊息資料型別gm_ros_package::test
看一下服務訊息資料型別的具體形式:
應用程式碼:
//server端
#include "ros/ros.h"
#include "gm_ros_package/objectPosition.h"
#include "gm_ros_package/test.h"
bool process_position(gm_ros_package:: test::Request &req,gm_ros_package::test::Response &res)
{
ROS_INFO("x:%f,y:%f,z:%f",req.points.point[0].x,req.points.point[0].y,req.points.point[0].z);
res.back = 12;
return true;
}
int main(int argc,char** argv)
{
ros::init(argc,argv,"recive_positon_node" );
ros::NodeHandle nh;
ros::ServiceServer service = nh.advertiseService("object_position",process_position);
ROS_INFO("wait the position message!");
ros::spin();
return 0;
}
//client端
#include "ros/ros.h"
#include "gm_ros_package/objectPosition.h"
#include "gm_ros_package/Points.h"
#include "geometry_msgs/Point.h"
#include "gm_ros_package/test.h"
#include <iostream>
using namespace std;
int main(int argc,char** argv)
{
ros::init(argc,argv,"send_position_node");
ros::NodeHandle nh;
ros::ServiceClient client = nh.serviceClient<gm_ros_package::test>("object_position");
gm_ros_package::test position;
gm_ros_package::Points points;
geometry_msgs::Point point[2];
point[0].x = 1.0;
point[0].y = 2.0;
point[0].z = 3.0;
point[1].x = 11.0;
point[1].y = 21.0;
point[1].z = 3.10;
//特別注意這裡賦值的形式
std::vector<geometry_msgs::Point> ar(point,point+2);
points.point = ar;
position.request.points = points;
if(client.call(position))
{
ROS_INFO("the progress is :%ld",position.response.back);
}
else
{
ROS_ERROR("Fail to call service");
}
}
總結
對於自己定義的複雜資料型別,當使用時,需要從最內層逐層的向外填充賦值。