I'm having trouble understanding how to save subscribed topic data (strings) in roslibpy to variables. In former research I've stumbled upon this thread Roslibpy Subscribe String data, but I'm still stuck. Ideally I'd have msg['data'] stored into a variable that I use later on.
All I was able to do so far is print the data that was subscribed for this topic, but I need to forward it. I have also tried returning msg['data'] in my callback function, but that wouldnt work.
from __future__ import print_function
import roslibpy
def callback(msg):
print(msg['data'])
client = roslibpy.Ros(host='localhost', port=9090)
client.run()
listener = roslibpy.Topic(client, '/chatter2', 'std_msgs/String')
listener.subscribe(callback)
try:
while True:
pass
except KeyboardInterrupt:
client.terminate()
I'm not sure there is much merit in using roslibpy directly instead normal subscribers. That said, you also cannot return data from a callback; at least in a useful way. This is because callbacks will be running asynchronously and have nowhere to actually return to.
What you're looking for is simply having a global variable that updates every time the callback is called.
callback_data = None
def callback(msg):
global callback_data
callback_data = msg['data']
def get_lastest_data():
global callback_data
print(callback_dadta)
As an unrelated point I would also suggest adding a ros Rate
to your main loop. This will help optimize and reduce CPU load for your node. Issues can also pop up when not allowing ros nodes proper time to sleep.