Writing a Subscriber (Python)

Create a package

First of all, you will have to create a new package, where you will place the code for your Publisher node. For this, you need to be in your ROS2 workspace src folder.

cd ~/ros2_ws/src

Now, execute the following command to create the package:

ros2 pkg create --build-type ament_python subscriber_py --dependencies rclpy std_msgs

You will get an output similar to this one:

This will automatically generate your package and all its necessary files and folders. Now, navigate to the subscriber_py/subscriber_py folder in order to create your file.

Write the code

Inside the subscriber_py/subscriber_py folder, create a new file named subscriber.py. Into this file, you will copy the following code

import rclpy
from rclpy.node import Node
from std_msgs.msg import Int32
​    
​class SimpleSubscriber(Node):
​    
    def __init__(self):
        super().__init__('simple_subscriber')
        self.subscription = self.create_subscription(Int32, 'counter', self.topic_callback, 10)
        self.subscription

    def topic_callback(self, msg):
        self.get_logger().info('I heard: "%s"' % msg.data) 
​    
​def main(args=None):
​   rclpy.init(args=args)
​   simple_subscriber = SimpleSubscriber()
​   rclpy.spin(simple_subscriber)
​   simple_subscriber.destroy_node()
​   rclpy.shutdown()

​if __name__ == '__main__':
​   main()

Review the code

First, we define our class, which inherits from the Node class.

class SimpleSubscriber(Node):

Next, we have the constructor of our class:

def __init__(self):

Within the constructor, we are initializing our node by calling to the constructor of the superclass Node.

super().__init__('simple_subscriber')

Also within the constructor, we create our subscription object. Note that the subscription object is bound to a function named topic_callback, which we will see next. This function will be triggered every time a new message is published into the /counter topic.

self.subscription = self.create_subscription(Int32, 'counter', self.topic_callback, 10)

Next we have the definition of the topic_callback function we introduced before. Inside this function, we are just generating a log message, which will print the contents of the msg.data variable. This variable will contain the message published into the /counter topic. Remember that this function will be triggered every time a new message is published into the /counter topic.

def topic_callback(self, msg):
        self.get_logger().info('I heard: "%s"' % msg.data)

Finally, on the main function, all we do is to create a SimpleSubscriber object, and make it spin until somebody shuts down the program (Ctrl+C).

def main(args=None):
    rclpy.init(args=args)
    simple_subscriber = SimpleSubscriber()
    rclpy.spin(simple_subscriber)
    simple_subscriber.destroy_node()
    rclpy.shutdown()

Modify the setup.py file

In the entry_points section of your setup.py file, add the following lines:

entry_points={
    'console_scripts': [
        'subscriber_node = subscriber_py.subscriber:main'
    ],
},

This will generate an executable, which points to the main function from the subscriber.py file, which is inside the subscriber_py folder.

Compile the package

First of all, let's go the ros2_ws folder in order to be able to compile.

cd ~/ros2_ws;

Let's now execute the colcon command in order to build our node.

colcon build --symlink-install

You will get an output like the following one:

Finally, let's source the workspace.

source ~/ros2_ws/install/setup.bash

Testing the Subscriber

Let's run our subscriber with the following command:

ros2 run subscriber_py subscriber

Now, in order to visualize the output, let's execute the following command:

ros2 topic pub /counter std_msgs/Int32 "{data: '5'}"

From the Shell where you executed the Subscriber, you will get the following:

And from the Shell where you publisher into the topic, you wll get the following:

Practice Online

Also, you can test this tutorial in ROSDS, using a ROSject which already contains all the code described in it. You can get the ROSject by clicking on the button below:

Above: Get ROSDS ROSject

The link above will take yo a page like the below one:

Now, you just need to Sign In (or Sign Up if you don't have an account yet) to ROSDS in order to launch the ROSject.