ROS Subscribe to multiple topics with single function
Thanks for feedback and help in advance,
I want to give input of topic names, initial data and data_type as dictionary to a function, and that function will subscribe to each topic and save data to dictionary. This is what I have done so far.
Example input
ros_topics = {"rosTopic1": {"data": None,
"type": "msg_type1"},
"rosTopic2": {"data": None,
"type": "msg_type2"},
"rosTopic3": {"data": None,
"type": "msg_type3"}}
I can subscribe to multiple topics and show their output message, however I couldn't save them into dictionary.
My function so far
def subscribe_topics(self):
for key in self.ros_topics.keys():
rospy.Subscriber(name=key,
data_class=self.ros_topics[key]["type"],
callback=self.common_callback)
def common_callback(self, msg):
print("####")
# Want to store msg.data to ros_topics[key]["data"], however I couldn't transfer **key**
print(msg)
print("####")
- Python 3.8
- ROS Noetic
- Ubuntu 20.04
As someone fairly new to ROS, the
"msg_type1"
within double inverted commas sort of threw me off. So for anyone else stuck there, it is apparently not supposed to be a string containing the name of the type of message (for e.g. NOT... {"rosTopic1": {"data": None, "type": "nav_msgs/Odometry"} ...
).Rather, here is supposed to be the object itself, for eg
... {"rosTopic1": {"data": None, "type": Odometry} ...
This is with the assumption that you have already added the required import line. For this case:
from nav_msgs.msg import Odometry
Yes, you are correct, I write them in that way to just show any msg type