Unsubscribing from topics [closed]
Hi there. I'm trying to implement a feature that would allow me to unsubscribe and stop publishing messages to certain topics, this is so that another node may begin publishing and subscribing to said topics. However when attempting this I am able to subscribe without a problem, but the nodes are never able unsubscribe and instead every node ends up publishing, causing unwanted messages to be sent and received. Below is an example of the code I am using to unsubcribe from the topics.
def unsubscribe_node(self):
# Function to unsubscribe a node from its topics and stop publishing data
with self.subscriber_lock:
self.is_offloaded = True
self.face_box_sub.unregister()
self.output_image_pub.unregister()
self.motor_commands_pub.unregister()
And here is the resubscribe function:
def resubscribe_node(self):
# Function to resubscribe and republish the nodes data
with self.subscriber_lock:
self.is_offloaded = False
self.output_image_pub = rospy.Publisher(self.output_image, Image, queue_size=self.queue_size)
self.face_box_sub = rospy.Subscriber(self.face_box_coordinates, FaceBox, self.update_face_box, queue_size=self.queue_size)
self.motor_commands_pub = rospy.Publisher(self.motor_commands, MotorCommand, queue_size=self.queue_size)
Is there anything I am doing wrong that I have missed?
Any help you guys can give would be great.
Is there any reason why you want to unsubscribe? The ROS topic system is designed such that you can have multiple publishers and subscribers on one topic. This is less confusing, because when you do "rostopic list", you see the complete output. I suggest you simply stop calling the "publish" method.
In roscpp, the Subscriber class has a shutdown() method. Is unregister the right method?
I have never had to use it, but from the class reference, it seems shutdown() is the right method:
Unsubscribe the callback associated with this Subscriber. This method usually does not need to be explicitly called, as automatic shutdown happens when all copies of this Subscriber go out of scope
Even though methods might exist to do what you want to, I think there are conceptual flaws. @Valts' comment is correct.
Thanks for your responses guys. I do actually need to unsubscribe the node because the program is meant to simulate computational offloading by doing so. shutdown() doesn't seem to do anything for me :/ The terminal outputs seem to show that the unsubscribing works, but the Node_Graph doesn't.
Do you need the graph to reflect it? The callbacks aren't being fired, which, unless I misunderstand your purpose, should be sufficient, no?
Subscribers shut down automatically when they go out of scope. Just try setting them to
None
. Should do the trick.Setting it to None also seems to do the trick but still no reflection on the node graph. I suppose editing the node graph source code will be the solution. Thanks for your help guys :)