Change subscribed topic/subscriber based on condition during runtime
I have a robot with a front and back camera. I've got a callback function in my node that can be used for the topics from either of the cameras. I want the callback to subscribe to one of the two topics depending on a condition.
Something like:
If front mode engaged:
ros::Subscriber subPCL = n.subscribe<PointCloud>("/front_cloud", 10, pclCallback);
If back mode engaged:
ros::Subscriber subPCL = n.subscribe<PointCloud>("/back_cloud", 10, pclCallback);
During runtime, the operation mode can change from front to back depending on which direction the robot is driving. So the topic the callback subscribes to should change.
Currently, I just initialise one subscriber in my main function when starting the node but this will create conflicts if I want to do the same for two.
I have a service callback in the same node that receives the direction the robot is going, which I thought I could use.
bool startrowCallback(row_follower::start_row_mode::Request &req, row_follower::start_row_mode::Response &res){
if (!rowMode){
rowMode = true;
drivingDirection = req.direction;
if (drivingDirection = "front") {
ros::Subscriber subPCL = n.subscribe<PointCloud>("/front_cloud", 10, pclCallback);
}
if (drivingDirection = "back"){
ros::Subscriber subPCL = n.subscribe<PointCloud>("/back_cloud", 10, pclCallback);
}
res.done = true;
}
else{
res.done = false;
}
return res.done;
}
But I'm not sure that is the right place to initialise a subscriber and if it the callback will get called with ros::spin in the main function. As I'm not passing the node handle from the main function I imagine what I wrote above won't compile. What would be the best way of doing this?