ROS How to pass a callback variable into another file?

Category: python ros (7 Views)

I have a callback function in a file "" that constantly recieves incoming data but updates a global variable every 3 seconds:

last_color = ""
last_calltime = datetime.strptime("00:00:00","%H:%M:%S")

def callback(data):
   global last_calltime, last_color
   cube =
   t = time.localtime()
   tf = time.strftime("%H:%M:%S",t)
   current_time = datetime.strptime(tf, "%H:%M:%S")
   delta_time = current_time - last_calltime

if abs(delta_time.total_seconds()) >= 3:
    if "Red" in cube:
        last_color = "Red"
    elif "Green" in cube:
        last_color = "Green"
        last_color = "Blue"

    t = time.localtime()
    tf = time.strftime("%H:%M:%S",t)
    last_calltime = datetime.strptime(tf, "%H:%M:%S")

    return last_color

if __name__ == '__main__':

    rospy.Subscriber ('/topic',String, callback)

In another file, I need to reference this "last_color" variable that updates. So far the function I have in this file:

from color import last_color
    a = 0

    def observe_color(a)
       if a == 0:
         return last_color 
         return "None"

I need this to return the updated variable from the "" file but it only returns the initialized value for last_color which is "". How can I do this?

🔴 No definitive solution yet

📌 Solution 1

I don't think it's gonna work that way. How about save the value of last_color to a file and monitor it ? Because to me you run 2 separated programs, 1 with the ROS and another just to monitor last_color

while True:
    with open(filename, 'r') as f:
        color = f.readline()

When write to file in the main, you could also append the read value and also the time, to get timeline data.

📌 Solution 2

When you import something in Python, you're effectively asking it to execute everything in that module in the same runtime as your current program.

Suppose I have some module with variable last_color='green'

And in a different program I have from color import last_color

The last_color that exists in and the last_color that exists in are different places in computer memory - they do not reference the same string value.

A quick (and maybe dirty) solution to this is just to re-import the module every time you want to observe one of its member variables.