在做ldiar slam的時候,最常用的當屬topic,偶爾也會用一下service,action則很少使用。現在一塊來看一下topic的使用。
一、topic的使用
topic的消息訂閱和發布
#include<ros/ros.h>
#include<rosbag/bag.h>
#include<rosbag/view.h>
#include<std_msgs/String.h>
#include<pcl/point_types.h>
#include<pcl/point_cloud.h>
#include<pcl/conversions.h>
#include<pcl_conversions/pcl_conversions.h>
#include<opencv2/opencv.hpp>#include<image_transport/image_transport.h>
#include<cv_bridge/cv_bridge.h>
#include<sensor_msgs/PointCloud2.h>
#include<sensor_msgs/Imu.h>
#include<nav_msgs/Odometry.h>
#include<sensor_msgs/LaserScan.h>
#include<sensor_msgs/Range.h>
#include<turtlesim/Spawn.h>
#include<std_srvs/Trigger.h>class DataProcess
{public:DataProcess(){}public:void processPointCloud2(const sensor_msgs::PointCloud2::ConstPtr& pc){}void imuCallback(const sensor_msgs::Imu::ConstPtr& imuMsg){std::cout<< imuMsg->linear_acceleration.x<< " "<< imuMsg->linear_acceleration.y<< " "<< imuMsg->linear_acceleration.z<< " \n";}pcl::PointCloud<pcl::PointXYZI> pointxyz;pointxyz.width = 100;pointxyz.height = 1;pointxyz.resize(pointxyz.height * pointxyz.width);srand(time(nullptr));for(int i = 0;i < 100; i ++){pointxyz.points[i].x = (rand()% 1000) / 10.0;pointxyz.points[i].y = (rand()% 1000) / 10.0;pointxyz.points[i].z = (rand()% 1000) / 10.0;}//-------------------------------------------點云的生成和轉化----------------------------順利完成---------------------// 這個函數在pcl_conversion./pcl_conversion.h文件中sensor_msgs::PointCloud2 pointCloudMsg;pointCloudMsg.header.stamp = ros::Time().now();pointCloudMsg.header.frame_id = "/camera_init";pcl::toROSMsg(pointxyz,pointCloudMsg);pcl::PointCloud<pcl::PointXYZI> pointxyzi2;pcl::fromROSMsg(pointCloudMsg, pointxyzi2);for( int i = 0; i < pointxyzi2.points.size();i ++ ){std::cout<< pointxyzi2.points[i].x<<" "<< pointxyzi2.points[i].y<<" "<< pointxyzi2.points[i].z<<"\n";}pcl::PointCloud<pcl::PointXYZI> point3;pcl::moveFromROSMsg(pointCloudMsg,point3);for( int i = 0; i < point3.points.size();i ++ ){std::cout<< point3.points[i].x<<" "<< point3.points[i].y<<" "<< point3.points[i].z<<"****\n";}}
二、service的使用
以spawn為例子,學習service的使用。這個例子比較簡潔,這樣很容易學會。
1)客戶端
#include<ros/ros.h>
#include<turtlesim/spawn.h>int main(int argc, char** argv)
{turtlesim::Spawn spawn;spawn.request.x = 0.0;spawn.request.y = 1.0;spawn.request.theta = 1.0;spawn.request.name = "turtle2";ros::service::waitForService("/showspawn");ros::ServiceClient client = nh_.serviceClient<turtlesim::Spawn>("/showspawn");client.call(spawn);
}
2)服務端
#include<ros/ros.h>
#include<turtlesim/Spawn.h>bool srvCallback1(turtlesim::Spawn::Request &req, turtlesim::Spawn::Response& respond){respond.name = req.name;std::cout<< respond.name <<std::endl;return true;}
int main(int argc, char** argv)
{ros::init(argc, argv, "rosbaglearn1");ros::NodeHandle nh_;ros::ServiceServer srv = nh_.advertiseService("/showspawn", srvCallback1 );ros::spin();return 0;
}