ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question

Multiple publishers and subscribers in a class

asked 2017-01-18 03:39:04 -0500

ashwath1993 gravatar image

I am trying to build single c++ file which contains a class that handles both subscribers and publishers. I want to publish multiple instance of a msg (representing different sensors) using the same class.
I wanted to know if such a system is possible on roscpp

#include <ros/ros.h>
class SubscribeAndPublish
//Topic you want to publish
pub_ = n_.advertise<ros_work::sensor>("sensors", 1000);
ros::Rate loop_rate(10);
pub_.publish(msg); //publishes the msg
ros::spinOnce(); //done to handle callbacks
loop_rate.sleep(); //sleep till the time is done --10
void input()
  int id,t;
  long int mem;
  ROS_INFO("Enter the ID: ");
  scanf("%d", &id);
  ROS_INFO("Enter the memory: ");
  scanf("%ld", &mem); = id;
  msg.memory = mem; = "test";
msg.state = true;

ros::NodeHandle n_; 
ros::Publisher pub_;
ros_work::sensor msg;
//ros::Subscriber sub_;

};//End of class SubscribeAndPublish

int main(int argc, char **argv)
 //Initiate ROS
 ros::init(argc, argv, "sensors_class");

 //Create an object of class SubscribeAndPublish that will take care of everything
 SubscribeAndPublish SAPObject[4];

 return 0;
edit retag flag offensive close merge delete



Why don't you just try?

NEngelhard gravatar image NEngelhard  ( 2017-01-18 15:09:38 -0500 )edit

I ran the above code. The problem is that only one instance can publish and since I have a while loop the next instance never gets called. So I am unable to implement a simple pub/sub using the above class for more than 1 instance.

ashwath1993 gravatar image ashwath1993  ( 2017-01-19 02:29:58 -0500 )edit

You could let every instance create a thread so that you don't have a blocking loop.

NEngelhard gravatar image NEngelhard  ( 2017-01-19 05:30:56 -0500 )edit

1 Answer

Sort by ยป oldest newest most voted

answered 2017-01-19 20:13:03 -0500

Dirk Thomas gravatar image

You can replace your loops which use a rate-sleep with a timer and perform your action in the timer callbacks. See the corresponding timer tutorial: Then you only need a single spin() call at the end of your main.

edit flag offensive delete link more

Question Tools

1 follower


Asked: 2017-01-18 03:39:04 -0500

Seen: 1,960 times

Last updated: Jan 19 '17