ROS Python global variables storing last data. Can we clear the data if there is no publishing through that topic?

asked 2021-06-10 00:54:34 -0500

Sai gravatar image

Hello Guys,

I am having a issue with python class and ROS. Here is my publisher code.(

#!/usr/bin/env python

import rospy
from std_msgs.msg import Int32MultiArray
import time

class OverloadingTest:
    def __init__(self):
    rospy.init_node("overload_variable_test", anonymous=True) = rospy.Publisher("overload", Int32MultiArray, queue_size=10)
    self.test_arr = [0,0,0]
    self.rate = rospy.Rate(10)

def publish(self):
    i = 0
    while not rospy.is_shutdown():
        self.test_arr[0] = i+1
        self.test_arr[1] = i+2
        self.test_arr[2] = i+3
        i = self.test_arr[0]
        arr = Int32MultiArray() = self.test_arr 

if __name__ == "__main__":
      olg = OverloadingTest()

In the above code, I am publishing a list of three integer values. Here is the subscriber code.(

    #!/usr/bin/env python

import rospy
import time
from std_msgs.msg import Int32MultiArray

#testdata = None
class OverloadingSubscriber:
    def __init__(self):
        self.testdata = None

    def callback(self, data):
        # global testdata

    def overloading_sub(self):
        #global testdata
        rospy.Subscriber("overload", Int32MultiArray, self.callback, queue_size=10)
        while not rospy.is_shutdown():
            #Do Something

if __name__ == '__main__':
    olg1 = OverloadingSubscriber()

In the above subscriber Code, overloading_sub function subscribes the publishing data and goes to callback and updating the global variable.

This code works as long as the publisher is publishing the data. But, when the publisher stops publishing. Subscriber stores the last data in a global variable and keep printing the last value.

In my use case, when there is no data coming from publisher, subscriber should clear the value and give me 'None'.

Is there any way to clear the global variable? or how to identify whether particular topic is sending data or not?

I am stuck with this issue guys. Help required.

Thanks in Advance.

edit retag flag offensive close merge delete


Hello, Did you find any solution to this problem?

08beeqtufail gravatar image 08beeqtufail  ( 2023-02-01 04:05:06 -0500 )edit