Multiple publishers and subscribers in a class
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;
}
Why don't you just try?
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.
You could let every instance create a thread so that you don't have a blocking loop.