ros中非长连接的通信使用topic的方式,publisher向topic发布消息,subscriber订阅topic消息,对于非应答模式的通信适合使用该模式,如下图
接下来我们实现一个发布者和订阅者
在实现订阅者和发布者的时候我们需要先创建一个功能包
cd catkin_ws/src/
catkin_create_pkg learning_topic roscpp rospy std_msgs geomery_msgs turtlesim
cd catkin_ws/src/learning_topic/src
创建 velocity_publisher.cpp 发布者
#include
#include
int main(int argc, char **argv)
{
// ros 节点初始化
ros::init(argc, argv, "velocity_publisher");
// 创建节点句柄
ros::NodeHandle node;
// 创建一个publisher,发布名为/turtle1/cmd_vel的topic, 消息类型为geometry_msgs::Twist,队列长度为10
ros::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/s
vel_msg.linear.x = 0.5;
// 角速度z方向0.2弧度/s
vel_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;
}
vi catkin_ws/src/learning_topic/CMakeLists.txt
添加如下内容
add_executable(velocity_publisher src/velocity_publisher.cpp)
target_link_libraries(velocity_publisher ${catkin_LIBRARIES})
cd catkin_ws
# 编译
catkin_make
# 设置环境变量
source devel/setup.sh
# 启动ros核心程序
roscore
另开一个终端
cd catkin_ws
source devel/setup.sh
# 启动海归仿真器
rosrun turtlesim turtlesim_node
另开一个终端
cd catkin_ws
source devel/setup.sh
# 启动发布者
rosrun learning_topic velocity_publisher
cd catkin_ws/src/learning_topic/src
创建 pose_subseriber.cp
#include
#include
// 订阅者回掉函数,回掉消息里面处理流程要简单
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,消息队列为10
ros::Subscriber pose_sub = node.subscribe("/turtle1/pose", 10, pose_callback);
// 等待发布者消息
ros::spin();
}
vi catkin_ws/src/learning_topic/CMakeLists.txt
添加如下内容
add_executable(pose_subseriber src/pose_subseriber.cpp)
target_link_libraries(pose_subseriber ${catkin_LIBRARIES})
cd catkin_ws
# 编译
catkin_make
# 设置环境变量
source devel/setup.sh
# 启动ros核心程序
roscore
上面小海龟已经动起来了,接下来启动订阅者就能知道小海龟的实时位置
另开一个终端
cd catkin_ws
source devel/setup.sh
# 启动订阅者
rosrun learning_topic pose_bseriber
这个时候就会在终端上打印小海龟的实时位置