How to use Object-Oriented Architecture In Python

It is always advisable to opt for creating instances of your nodes. This makes the robot-human analogy or robot-‘mini-mailbox’ analogy much more apparent and easier to understand, if not just the idea of debugging.

In this example, we will try to obtain the velocity at which our turtlebot moves. Save this file as subscriber.py – for the convenience alone.

Python3




#!/usr/bin/env python
  
import rospy
# in this example we try to obtain linear
# and angular velocity related information.
# So we import Twist
from geometry_msgs.msg import Twist
  
  
class basic_subscriber:
  
    def __init__(self):
        # initialize the subscriber node now.
        # here we deal with messages of type Twist()
        self.image_sub = rospy.Subscriber("/cmd_vel"
                                          Twist, self.callback)
        print("Initializing the instance!")
  
    def callback(self, Twist):
        
        # now simply display what
        # you've received from the topic
        rospy.loginfo(rospy.get_caller_id() + "The velocities are %s",
                      Twist)
        print('Callback executed!')
  
  
def main():
    # create a subscriber instance
    sub = basic_subscriber()
      
    # follow it up with a no-brainer sequence check
    print('Currently in the main function...')
      
    # initializing the subscriber node
    rospy.init_node('listener', anonymous=True)
    rospy.spin()
  
if __name__ == '__main__':
    try:
        main()
    except rospy.ROSInterruptException:
        pass


Explanation

  • Code execution begins in the try-except block. The function main( ) is called here.
  • In main( ):
    • Create an object or instance of type basic_subscriber(). This initializes the class.
    • Execution continues onto the next line where we create and initialize the node ‘listener’.
    • rospy.spin( ) ensures that are code is executing in an infinite loop until a shutdown signal is received.
  • In the basic_subscriber class, we use the constructor equivalent __init__(self) to define the attributes of the class.
  • The subscriber entity is now defined.
    • It subscribes to the ‘/cmd_vel’ topic.
    • The type of message we have subscribed to here is of type Twist() – the one cluing us on the velocities.
    • The final field calls the callback( ) function now.
      • Here is where we print the subscribed information onto the terminal and also to a log file.
      • In order to confirm that our callback( ) function was executed successfully, we print a simple message ‘Callback executed’.

Be sure to make this file an executable. In order to do so, navigate to your package’s directory and type the following:

$ chmod +x subscriber.py

Deploying ROS

First, run turtlebot3 from the Terminal.

$ roscore

# Press Ctrl+Shift+T to open a new terminal

$ caktin_make

# always source your base files in every new terminal that you open.

$ source devel/setup.bash

# now run the turtlebot3 simulator

$ roslaunch turtlebot3_gazebo turtlebot3_world.launch

You will notice that gazebo launches and the default Once again, in a new Terminal, type the following:

$ source devel/setup.bash

$ roslaunch turtlebot3_teleop turtlebot3_teleop_key.launch

You will now be able to control the turtlebot3 simulator which opens in a separate window using your keyboard. Now run your Subscriber script. In a new terminal, run the following:

$ rosrun <package_name> subscriber.py

Output:

When the turtlebot3 is stationary.

After moving the turtlebot3 using  teleop_key.

Code demonstration



ROS Subscribers using Python

Writing a Subscriber for a bot in simulation might seem to bring with it a load of complexity, but it definitely is not so. Progressing through the tutorials for Robot Operating Systems (ROS) offers a great deal of knowledge, however, it might fare well to provide more insight. This article aims to provide an understanding of how Subscribers work and are better written in Python. 

Similar Reads

ROS Subscribers

Since robots primarily intend to automate what humans would otherwise do, we will draw parallels between simple human anatomy or man-made paraphernalia, and the robot’s construction to build perspective. Therefore, it is crucial that the reader understands what ROS nodes and ROS topics are....

Prerequisites

In order to work along with the examples, it is necessary to have the following:...

Using Object-Oriented Architecture

...