ROS Python global variables storing last data. Can we clear the data if there is no publishing through that topic?
Hello Guys,
I am having a issue with python class and ROS. Here is my publisher code.(pub.py)
#!/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)
self.pub = 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()
arr.data = self.test_arr
self.pub.publish(arr)
time.sleep(1)
self.rate.sleep()
if __name__ == "__main__":
olg = OverloadingTest()
olg.publish()
In the above code, I am publishing a list of three integer values. Here is the subscriber code.(sub.py)
#!/usr/bin/env python
import rospy
import time
from std_msgs.msg import Int32MultiArray
#testdata = None
class OverloadingSubscriber:
def __init__(self):
rospy.init_node("overloading_subscriber",anonymous=True)
self.testdata = None
def callback(self, data):
# global testdata
self.testdata= data.data
#print(data.data)
def overloading_sub(self):
#global testdata
rospy.Subscriber("overload", Int32MultiArray, self.callback, queue_size=10)
while not rospy.is_shutdown():
print(self.testdata)
#Do Something
rospy.spin()
if __name__ == '__main__':
olg1 = OverloadingSubscriber()
olg1.overloading_sub()
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.
Hello, Did you find any solution to this problem?