ROS启动后 多个Node节点都需要到ROS Master进行注册,每个node都有自己的逻辑功能,有时候需要数据传递,不直接通讯的原因是为了解耦,设计了TOPIC
原理图如下:
ROS将发布消息的定义为**Publisher(发布者),将接收消息的一方定义为**Subscriber(订阅者)
多对多的关系,哪个node需要获取消息直接去取就可以,像一个容器,可以多个node同时取数据,发数据
注意:c++回调在主线程 python回调在子线程
c++.实现代码:
publisher
#include <iostream>
#include "ros/ros.h"
#include "std_msgs/String.h"
using namespace std;
int main(int argc, char *argv[]) {
string nodeName = "cpp_publisher";
// 初始化节点
ros::init(argc, argv, nodeName);
//创建一个节点
ros::NodeHandle nodeHandle;
string publisherName = "cpp_publisher";
// 创建topic发送者
const ros::Publisher &publisher = nodeHandle.advertise<std_msgs::String>(publisherName, 5);
ros::Rate rate(1);
int i = 0;
while (ros::ok()) {
std_msgs::String msg;
msg.data = "发送的消息" + to_string(i);
publisher.publish(msg);
i += 1;
rate.sleep();
}
return 0;
}
c++ subscriber
#include <iostream>
#include "ros/ros.h"
#include "std_msgs/String.h"
using namespace std;
void callBack(std_msgs::String::ConstPtr msg) {
cout << msg->data << endl;
}
int main(int argc, char *argv[]) {
string nodeName = "cpp_sbuscribe";
// 初始化节点
ros::init(argc, argv, nodeName);
// 创建节点
ros::NodeHandle nodeHandle;
string topicName = "cpp_publisher";
// 创建接收者
/** 参数1:topic 名称 和publisher中的保持一致
* 参数2:队列大小
* 参数3:回调函数
* 返回的类型用ctrl+alt+v 自动补全
*/
const ros::Subscriber &subscriber = nodeHandle.subscribe<std_msgs::String>(topicName, 5, callBack);
//阻塞线程
ros::spin();
}
python: publisher
#!/usr/bin/env python
#coding:utf-8
import rospy
from std_msgs.msg import String
if __name__ == '__main__':
nodeName = 'py_publisher'
rospy.init_node(nodeName)
topicName = 'py_topic'
publisher = rospy.Publisher(topicName,String,queue_size=5)
rate = rospy.Rate(1)
i = 0
while not rospy.is_shutdown():
date = String()
date.data = 'hello{}'.format(i)
i+=1
publisher.publish(date)
rate.sleep();
python:subscriber
#!/usr/bin/env python
#coding:utf-8
import rospy
from std_msgs.msg import String
def callBack(data):
print data
if __name__ == '__main__':
nodeName = 'py_subscriper'
rospy.init_node(nodeName)
topicName = 'py_topic'
subscriber = rospy.Subscriber(topicName,String,callBack)
rospy.spin()