1.6 Subscribing to topics in Python

1.6 Subscribing to topics in Python#

Printing the data from a topic in the commandline might be useful for debudding purposes, but with that you will not be able to program your robot. For this we need to use the ROS2 Python or C++ API. In order to connect to this topic from our own node, we need to have some more information of this topic. We already have the name (‘/mirte/distance/left’), but we also need to know the data type (what kind of information is it sending.

/sensor_msgs/Range
mirte$ ros2 topic type /mirte/distance/left

info

ROS already has lots of predefined message types which are commonly used in robots. For example:

  • std_msgs: All kinds of standard basic types like Int, Float, etc.

  • sensor_msgs: All kinds of sensor types like Range, Image, etc.

You can find a list of all common interfaces here.

This shows us that is of type sensor_msgs/Range. But let’s also have a look at how this data is organized:

mirte$ ros2 interface show sensor_msgs/msg/Range

Please note the extra ‘msg’ part. This could be found by listing all interfaces ($ ros2 interface list). We can now see that the data we are interested in is in Range.range, which we could also see when we echo’d the topic. Now that we have both the type and the name, we can create our own node which listens to this data. Create a new node in your package and run it:

 1import rclpy
 2from rclpy.node import Node
 3from sensor_msgs.msg import Range
 4
 5class SubscriberExampleNode(Node):
 6   def __init__(self):
 7      super().__init__("subscriber_node")
 8      self._subscription = self.create_subscription(
 9         Range,
10         "/mirte/distance/left",
11         self.receive_message_callback,
12         1
13      )
14
15   def receive_message_callback(self, message):
16      self.get_logger().info("I got range: " + str(message.range))
17
18def main():
19   rclpy.init()
20   my_subscriber_node = SubscriberExampleNode()
21   try:
22      rclpy.spin(my_subscriber_node)
23   except KeyboardInterrupt:
24      return
[INFO] [1715670084.126321319] [subscriber_node]: I got range: 20.0

Since we ran colcon with –symlink-install, there is no need to build it again. So we can right away start the node. And if you like to, you can also see the ROS system using rqt_graph.