ros中非长连接的通信使用topic的方式,publisher向topic发布消息,subscriber订阅topic消息,对于非应答模式的通信适合使用该模式,如下图
接下来我们实现一个发布者和订阅者
1. 创建功能包
在实现订阅者和发布者的时候我们需要先创建一个功能包
cd catkin_ws/src/catkin_create_pkg learning_topic roscpp rospy std_msgs geomery_msgs turtlesim
2. 创建发布者
2.1. 创建代码
cd catkin_ws/src/learning_topic/src
创建 velocity_publisher.cpp 发布者
#include <ros/ros.h>
#include <geometry_msgs/Twist.h>int main(int argc, char **argv)
{// ros 节点初始化ros::init(argc, argv, "velocity_publisher");// 创建节点句柄ros::NodeHandle node;// 创建一个publisher,发布名为/turtle1/cmd_vel的topic, 消息类型为geometry_msgs::Twist,队列长度为10ros::Publisher turtle_vel_pub = node.advertise<geometry_msgs::Twist>("/turtle1/cmd_vel", 10);// 设置循环的频率ros::Rate loop_rate(10);int count = 0;while (ros::ok()){// 初始化geometry_msgs::Twist消息geometry_msgs::Twist vel_msg ;// 线速度x方向0.5m/svel_msg.linear.x = 0.5;// 角速度z方向0.2弧度/svel_msg.angular.z = 0.2;// 发布消息turtle_vel_pub.publish(vel_msg);ROS_INFO("Publish turtle velocity command [%0.2f m/s, %0.2f rad/s]", vel_msg.linear.x, vel_msg.angular.z);loop_rate.sleep();}return 0;
}
2.2. 修改cmake
vi catkin_ws/src/learning_topic/CMakeLists.txt
添加如下内容
add_executable(velocity_publisher src/velocity_publisher.cpp)
target_link_libraries(velocity_publisher ${catkin_LIBRARIES})
2.3. 编译
cd catkin_ws
# 编译
catkin_make
# 设置环境变量
source devel/setup.sh
# 启动ros核心程序
roscore
2.4. 启动仿真器
另开一个终端
cd catkin_ws
source devel/setup.sh
# 启动海归仿真器rosrun turtlesim turtlesim_node
此时屏幕上出现一个小海龟
2.5. 启动发布者
另开一个终端
cd catkin_ws
source devel/setup.sh
# 启动发布者
rosrun learning_topic velocity_publisher
这个时候看到小海龟在转圈
3. 创建订阅者
这里我们订阅小海龟的pos信息
3.1. 创建代码
cd catkin_ws/src/learning_topic/src
创建 pose_subseriber.cp
#include <ros/ros.h>
#include <turtlesim/Pose.h>// 订阅者回掉函数,回掉消息里面处理流程要简单
void pose_callback(const turtlesim::Pose::ConstPtr &msg)
{// 打印pos信息ROS_INFO("Turtle Pos: x:%0.6f, y:%0.6f", msg->x, msg->y);
}int main(int argc, char **argv)
{ros::init(argc, argv, "pose_subscriber");// 创建节点ros::NodeHandle node;// 创建一个订阅者,订阅 /turtle1/pose topic,消息队列为10ros::Subscriber pose_sub = node.subscribe("/turtle1/pose", 10, pose_callback);// 等待发布者消息ros::spin();
}
3.2. 修改cmake
vi catkin_ws/src/learning_topic/CMakeLists.txt
添加如下内容
add_executable(pose_subseriber src/pose_subseriber.cpp)
target_link_libraries(pose_subseriber ${catkin_LIBRARIES})
2.3. 编译
cd catkin_ws
# 编译
catkin_make
# 设置环境变量
source devel/setup.sh
# 启动ros核心程序
roscore
2.5. 启动订阅者
上面小海龟已经动起来了,接下来启动订阅者就能知道小海龟的实时位置
另开一个终端
cd catkin_ws
source devel/setup.sh
# 启动订阅者
rosrun learning_topic pose_bseriber
这个时候就会在终端上打印小海龟的实时位置