ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange |
1 | initial version |
I think you are asking something that makes use of #q63991 , the following example creates n subscribers and passes on information to the callback to be able to distinguish them:
#include "ros/ros.h"
#include "std_msgs/String.h"
void chatterCallback2(const std_msgs::String::ConstPtr& msg, const std::string topic)
{
ROS_INFO_STREAM(topic << ": I heard: " << msg->data.c_str());
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "listener");
ros::NodeHandle n;
std::vector<ros::Subscriber> subs;
int num = 10;
ros::param::get("~num", num);
for (size_t i = 0; i < num; ++i)
{
std::stringstream ss;
ss << "topic_" << i;
const std::string topic = ss.str();
ros::Subscriber sub = n.subscribe<std_msgs::String>(topic, 10,
boost::bind(chatterCallback2, _1, topic));
subs.push_back(sub);
}
ros::spin();
return 0;
}
A typical pattern a bit more complex than this would be to have a std::map using the topic names as keys and data in the callback is stored or manipulate using that map.
2 | No.2 Revision |
I think you are asking something that makes use of #q63991 , the following example creates n subscribers and passes on information to the callback to be able to distinguish them:
#include "ros/ros.h"
#include "std_msgs/String.h"
void chatterCallback2(const std_msgs::String::ConstPtr& msg, const std::string topic)
{
ROS_INFO_STREAM(topic << ": I heard: " << msg->data.c_str());
msg->data);
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "listener");
ros::NodeHandle n;
std::vector<ros::Subscriber> subs;
int num = 10;
ros::param::get("~num", num);
for (size_t i = 0; i < num; ++i)
{
std::stringstream ss;
ss << "topic_" << i;
const std::string topic = ss.str();
ros::Subscriber sub = n.subscribe<std_msgs::String>(topic, 10,
boost::bind(chatterCallback2, _1, topic));
subs.push_back(sub);
}
ros::spin();
return 0;
}
A typical pattern a bit more complex than this would be to have a std::map using the topic names as keys and data in the callback is stored or manipulate using that map.