Welcome to Raspberry Pi 4B repository
3.ROS2 Topic communications
ROS2 Topic communications
Topic communication is one of the most frequently used communication methods in ROS2, topic communication is based on the publish-subscribe model, there are publishers publishing data on a specified topic, subscribers as long as they subscribe to the data of the topic, they can receive data. Next, let's explain how to use the Python language to achieve topic communication between nodes.
1、Create a new workspace
terminal input:
mkdir -p ros2_ws/srccd ros2_ws/src
ros2_ws is the name of the workspace, and src is the directory where the feature packs are stored.
2、Create a new feature pack
terminal input:
xxxxxxxxxxcd ~/ros2_ws/srcros2 pkg create --build-type ament_python topic_pkg

Switch to topic_pkg folder, there are the following files and folders, the python program we wrote is placed under the topic_pkg folder under this directory, that is:
xxxxxxxxxx~/ros2_ws/src/topic_pkg/topic_pkg
3、Write the publisher python file
3.1、Program source code
Create a new file, named publisher_demo.py:
xxxxxxxxxxcd ~/ros2_ws/src/topic_pkg/topic_pkggedit publisher_demo.py
Copy the following sections into the file:
xxxxxxxxxximport rclpyfrom rclpy.node import Nodefrom std_msgs.msg import Stringclass Topic_Pub(Node): def __init__(self,name): super().__init__(name) self.pub = self.create_publisher(String,"/topic_demo",1) self.timer = self.create_timer(1,self.pub_msg) def pub_msg(self): msg = String() msg.data = "Hi,I send a message." self.pub.publish(msg) def main(): rclpy.init() pub_demo = Topic_Pub("publisher_node") rclpy.spin(pub_demo)This is achieved with the idea of modularity, which is conducive to porting and modifying the code. First define a class, the class name is Topic_Pub, there are two parts in it, one is init and the other is pub_msg. init is the initialization of the class itself, pub_msg the methods of the class, that is, as long as we create the objects of this class, we can use the variables and methods inside.
xxxxxxxxxx#Import the RCpy libraryimport rclpyfrom rclpy.node import Node#Import a String messagefrom std_msgs.msg import String #Create a Topic_Pub node subclass that inherits from the Node base class and pass in a parameter namedef __init__(self,name): super().__init__(name) #Create a publisher with create_publisher function and pass in the following parameters: #Topic data type, thread name, queue length to save messages self.pub = self.create_publisher(String,"/topic_demo",1) #Create a timer and enter the interrupt handler at intervals of 1s, passing in the following parameters: #The interval between execution of the interrupt function, interrupt the handler self.timer = self.create_timer(1,self.pub_msg)#Defines interrupt handlersdef pub_msg(self): msg = String() #Create a variable of type String msg msg.data = "Hi,I send a message." #Assign a value to the data in MSG self.pub.publish(msg) #Publish topic data #Main functiondef main(): rclpy.init() #initialize pub_demo = Topic_Pub("publisher_node") #To create a Topic_Pub class object, the parameter passed in is the name of the node rclpy.spin(pub_demo) #Execute the rclpy.spin function, pass in a parameter, the parameter is the Topic_Pub class object just created 3.2、Modify the setup.py file
terminal input:
xxxxxxxxxxcd ~/ros2_ws/src/topic_pkggedit setup.py
Locate the location as shown in the image below:

Add the following to 'console_scripts': []
x'publisher_demo = topic_pkg.publisher_demo:main'
Code explanation:

The name of the executable file is our custom, that is, which program we need to execute when ros2 run, the function package name is which function package your python file is located in, followed by the name of the python file, and the last main is the program execution entry. As long as it is a program written in python format, compile and generate executable files, you need to add it here in the above format.
3.3、Compile the workspace
xxxxxxxxxxcd ~/ros2_wscolcon build
Compile successfully, enter the following command to add the workspace to the system environment variable,
xxxxxxxxxxecho "source ~/ros2_ws/install/setup.bash" >> ~/.bashrc
Then, reopen the terminal or refresh the environment variable to take effect.
xxxxxxxxxxsource ./.bashrc
3.4、Run the program
terminal input,
xxxxxxxxxxros2 run topic_pkg publisher_demo
After the program runs successfully, there is no printing anything, we can view the data through the ros2 topic tool, first check whether this topic is published, terminal input,
xxxxxxxxxxros2 topic list

This topic_demo is the topic data defined in the program, next, we use ros2 topic echo to print this data, terminal input,
xxxxxxxxxxros2 topic echo /topic_demo

As you can see, the terminal prints "Hi, I send a message." msg.data = "Hi,I send a message" in our code." unanimous.
4、Write subscriber python files
4.1、Program source code
Create a new file, named subscriber_demo.py,
xxxxxxxxxxcd ~/ros2_ws/src/topic_pkg/topic_pkggedit subscriber_demo.py
Copy the following sections into the file,
xxxxxxxxxx#Import the relevant librariesimport rclpyfrom rclpy.node import Nodefrom std_msgs.msg import String
class Topic_Sub(Node): def __init__(self,name): super().__init__(name) #The create_subscription used to create the subscriber is: topic data type, topic name, callback function name, queue length self.sub = self.create_subscription(String,"/topic_demo",self.sub_callback,1) #Callback function executor: prints the received information def sub_callback(self,msg): print(msg.data)def main(): rclpy.init() #ROS2 Python interface initialization sub_demo = Topic_Sub("subscriber_node") #Create an object and initialize it rclpy.spin(sub_demo)4.2、Modify the setup.py file
terminal input,
xxxxxxxxxxcd ~/ros2_ws/src/topic_pkggedit setup.py
Locate the location as shown in the image below,

Add the following to 'console_scripts': [] in the format,
xxxxxxxxxx'subscriber_demo = topic_pkg.subscriber_demo:main'

4.3、Compile the workspace
xxxxxxxxxxcd ~/ros2_wscolcon build
After the compilation is completed, refresh the environment variables of the workspace.
xxxxxxxxxxsource ~/ros2_ws/install/setup.bash
4.4、Run the program
terminal input,
xxxxxxxxxx#Start the publisher noderos2 run topic_pkg publisher_demo #Start the subscriber noderos2 run topic_pkg subscriber_demo
As shown in the figure above, the terminal running the subscriber point prints the information published by the publisher / topic_demo.
You can use the following command to view the topic communication between the two nodes:
xxxxxxxxxxros2 run rqt_graph rqt_graph

5、summary
5.1、Python writes a framework for topic communicators

5.2、Modify the contents of setup.py file
To write a node program using Python, you need to modify the setup.py file, refer to the above content, and add and generate your own node program.