[roscpp] unsubscribe within a callback and resubscribe in while(ros::ok)
Hi there, as new to ros and c++, I have a question to ask about unsubscribe and resubscribe. I am working on a multi-quadrotor path planning project and need to define squad leader everytime the team split into new squads. In that case, the squad member will subscribe to its leader for further commanding. But I have trouble on how to unsubscribe old leader's command and resubscribe to a new leader's. Below is the part of code that doing this little function:
ros::Subscriber splitcmd_sub;
// get split command from the leader and determine leader(s) for squad(s)
void getsplitcmd(const geometry_msgs::Point::ConstPtr& msg)
{
//...some code to find out whom to follow
squad_leader_no = ...;
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "mycontrol_4");
ros::NodeHandle n;
ros::Rate cycle(8);
while(ros::ok()){
// ...some other code here
if(squad_leader_no == 1){splitcmd_sub = n.subscribe("/uav1/split_cmd", 1000, getsplitcmd);}
if(squad_leader_no == 2){splitcmd_sub = n.subscribe("/uav2/split_cmd", 1000, getsplitcmd);}
if(squad_leader_no == 3){splitcmd_sub = n.subscribe("/uav3/split_cmd", 1000, getsplitcmd);}
if(squad_leader_no == 4){splitcmd_sub = n.subscribe("/uav4/split_cmd", 1000, getsplitcmd);}
// ...some code here
ros::spinOnce();
cycle.sleep();
}
return 0;
}
After a numerous tests, only once I have the subscriber resubscribed. At other times, it just seem not to work at all(no disconnection and reconnection). Also, I have tried splitcmd_sub::shutdown()
within the callback, but it just did not work.
I have searched and read a lot of tutorials and questions by other people online, it seems that I will have to use boost::bind
if I want to pass parameters from callback to while() in main everytime it receives new messages. Could anybody tell me what to do if I want to unsubscribe a topic and resubscribe to another one at correct times, please?
Thanks a lot!
to be more clear, the publisher split_cmd has been defined and publishing in the same .cpp file
try using
if-else
to ensure in one loop only one call back andsplitcmd_sub::shutdown()
inside callback.I have tried those, but it did not work
It was my own mistake that caused the problem, and sorry about that! Anyway, thanks a lot for your time!