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

Multiple publishers and subscribers in a class

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

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
{
 public:
SubscribeAndPublish()
{
//Topic you want to publish
pub_ = n_.advertise<ros_work::sensor>("sensors", 1000);
input();
ros::Rate loop_rate(10);
while(ros::ok())
{
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);
  msg.id = id;
  msg.memory = mem;
  msg.name = "test";
msg.state = true;
}

private:
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];
 ros::spin();

 return 0;
 }
edit retag flag offensive close merge delete

Comments

1

Why don't you just try?

NEngelhard gravatar image NEngelhard  ( 2017-01-18 15:09:38 -0600 )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 -0600 )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 -0600 )edit

1 Answer

Sort by ยป oldest newest most voted
1

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

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: http://wiki.ros.org/roscpp_tutorials/... Then you only need a single spin() call at the end of your main.

edit flag offensive delete link more

Question Tools

1 follower

Stats

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

Seen: 1,997 times

Last updated: Jan 19 '17