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

subscriber callback in a python class is overwriting the class variables with the most recent data before the first callback processing finishes.

asked 2020-01-18 05:44:02 -0500

abstracto gravatar image

updated 2020-01-18 07:56:48 -0500

gvdhoorn gravatar image

I am on ROS Melodic. When a subscriber is receiving data at a faster rate than it could process, the class variables are being updated before the callback process is finished. For example, when I run below subscriber. When the first callback is triggered tracker is set to 1 and after 5 seconds it was supposed to print 1, now before the completion of these 5 seconds, the subscriber receives another data, the call back will update tracker to 2. Now, this value 2 is printed twice instead of 1 and then 2. I am trying to say that the tracker is being set to most recent callback value before even the print process has been finished.

class listener:
    def printer(self):
        rospy.sleep(5)
        print (self.tracker)
        print("Look Above for value")

    def callback(self, data):
        rospy.loginfo("I heard %s", data)
        self.tracker = self.tracker + 1
        self.printer()

    def __init__(self):

        rospy.init_node('listener', anonymous=True)
        self.tracker = 0
        rospy.Subscriber('/path_query', PathQuery, self.callback,
                         queue_size=1)
        rospy.spin()

if __name__ == '__main__':
    listener()
edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2020-01-18 09:20:06 -0500

tryan gravatar image

That is expected behavior the way your functions are written. The callback immediately increments self.tracker every time, and after 5 seconds, the print function displays whatever value it finds there. If you want to print the old value, pass it as an argument to the print function, so it won't matter what happens to self.tracker in the mean time:

class listener:
    def printer(self, value):
        rospy.sleep(5)
        print (value)
        print("Look Above for value")

    def callback(self, data):
        rospy.loginfo("I heard %s", data)
        self.tracker = self.tracker + 1
        self.printer(self.tracker)

    def __init__(self):

        rospy.init_node('listener', anonymous=True)
        self.tracker = 0
        rospy.Subscriber('/path_query', PathQuery, self.callback,
                         queue_size=1)
        rospy.spin()

if __name__ == '__main__':
    listener()
edit flag offensive delete link more

Question Tools

1 follower

Stats

Asked: 2020-01-18 05:37:43 -0500

Seen: 1,468 times

Last updated: Jan 18 '20