当前位置:网站首页>Ros2 topic (VIII)

Ros2 topic (VIII)

2022-07-05 06:50:00 Me and nano

ROS2 Robot operating system


Preface

Nodes realize various functions of robots , But these functions are not independent , There will be countless connections , One of the most important contact methods is topic , It is a bridge for transferring data between nodes .

One 、topic topic of conversation

1. Communication model

 Insert picture description here
Take two robot nodes as an example .A The function of the node is to drive the hardware device of the camera , Get the image information taken by the camera ,B The function of the node is video surveillance , Display the image captured by the camera to the user in real time . At this point, the slave node A To the node B The way of transferring image data , stay ROS in , We call it topic , It serves as a bridge , It realizes the data transmission in a certain direction between nodes .

2. Publish and subscribe model

From the perspective of the implementation of the topic itself , Based on DDS Release / Subscription model , What is publish and subscribe ?
 Insert picture description here
The characteristic of topic data transmission is from one node to another , The object that sends data is called the publisher , The object receiving data is called a subscriber , Every topic needs a name , The transmitted data also needs to have a fixed data type . Insert picture description here
How to put it? , The relationship between publish and subscribe is similar to , I created a publisher , I posted the news , I don't care what you subscribe to , Anyway, I sent the message to a channel , You can check my news after subscribing to the change , It can also be subscribed by many individuals . Of course, you can't see it without a subscription

3. Many to many communication

 Insert picture description here
Think about these things you can subscribe to , Is it not the only , Each of us can subscribe to many official account 、 newspaper 、 The magazine , These official account numbers 、 newspaper 、 Magazines can also be subscribed by many people , you 're right ,ROS The same is true of the topic in , The number of publishers and subscribers is not unique , It can be called a many to many communication model .

Because the topic is a many to many model , The rocker that issues the control command can have a , There can be 2 individual 、3 individual , Robots that subscribe to control commands can have 1 individual , There can be 2 individual 、3 individual , You can imagine this picture , It seems to be quite magical , If there are multiple nodes that send instructions , It is suggested that you should pay attention to prioritization , Otherwise, the robot may not know who to listen to .

4. asynchronous communication

Topic communication has another feature , That's asynchronous , This word may be heard for the first time by some students ? Asynchronous , As long as it refers to the data sent by the publisher , I don't know when subscribers will receive , This is called asynchrony .
The asynchronous feature also makes the topic more suitable for some periodically published data , Such as sensor data , Motion control instructions, etc , If some instructions with strong logic , For example, modify a parameter , Topic transmission is not appropriate .

5. Message structure

Last , Since it is data transmission , Publishers and subscribers have to unify the description format of data , You can't speak English alone , One is understood as Chinese . stay ROS in , The description format of topic communication data is called message , Corresponding to the concept of data structure in programming language . For example, here is an image data , It will contain the length and width pixel values of the image 、 Per pixel RGB wait , stay ROS There are standard definitions in .

The news is ROS An interface definition method in , It's not about programming languages , We can also pass .msg The suffix file defines itself , With such an interface , Various nodes are like building blocks , Splice through various interfaces , Make up a complex robot system .

Two 、 Topic examples

1.Hello World Topic communication

 Insert picture description here
Start the first terminal , Run the publisher node of the topic :

ros2 run learning_topic topic_helloworld_pub

 Insert picture description here
Start the second terminal , The subscriber node that runs the topic :

ros2 run learning_topic topic_helloworld_sub

 Insert picture description here

Publisher code parsing

import rclpy                                     # ROS2 Python Interface library 
from rclpy.node import Node                      # ROS2  Node class 
from std_msgs.msg import String                  # ** String message type **

"""
 Create a publisher node 
"""
class PublisherNode(Node):

    def __init__(self, name):
        super().__init__(name)                                    # ROS2 Node parent class initialization 
        self.pub = self.create_publisher(String, "chatter", 10)   # ** Create publisher object ( Message type 、 Topic name 、 The queue length )**
        self.timer = self.create_timer(0.5, self.timer_callback)  #  Create a timer ( Period in seconds , Callback function executed regularly )

    def timer_callback(self):                                     #  Create a callback function for timer cycle execution 
        msg = String()                                            # ** Create a String Message object of type **
        msg.data = 'Hello World'                                  # ** Fill in the message data in the message object **
        self.pub.publish(msg)                                     #  Post topic news 
        self.get_logger().info('Publishing: "%s"' % msg.data)     #  Output log information , Prompt that the topic release has been completed 

def main(args=None):                                 # ROS2 Node main entrance main function 
    rclpy.init(args=args)                            # ROS2 Python Interface initialization 
    node = PublisherNode("topic_helloworld_pub")     #  establish ROS2 Node object and initialize 
    rclpy.spin(node)                                 #  Loop waiting for ROS2 sign out 
    node.destroy_node()                              #  Destroy the node object 
    rclpy.shutdown()                                 #  close ROS2 Python Interface 

After writing the code, you need to set the compilation options of the function package , Let the system know Python Program entry , To open a feature pack setup.py file , Add the following entry point configuration :

    entry_points={
    
        'console_scripts': [
         'topic_helloworld_pub  = learning_topic.topic_helloworld_pub:main',
        ],
    },

Process summary
Analyze the above procedures , If we want to implement a publisher , The process is as follows :

Programming interface initialization
Create nodes and initialize
Create publisher object
Create and populate topic messages
Post topic news
Destroy the node and close the interface

Subscriber code parsing

import rclpy                      # ROS2 Python Interface library 
from rclpy.node   import Node     # ROS2  Node class 
from std_msgs.msg import String   # ROS2 Standard definition of String news 

"""
 Create a subscriber node 
"""
class SubscriberNode(Node):

    def __init__(self, name):
        super().__init__(name)                             # ROS2 Node parent class initialization 
        self.sub = self.create_subscription(\
            String, "chatter", self.listener_callback, 10) #  Create subscriber object ( Message type 、 Topic name 、 Subscriber callback function 、 The queue length )

    def listener_callback(self, msg):                      #  Create callback function , Execute the data processing after receiving the topic message 
        self.get_logger().info('I heard: "%s"' % msg.data) #  Output log information , Prompt to subscribe to the received topic messages 

def main(args=None):                               # ROS2 Node main entrance main function 
    rclpy.init(args=args)                          # ROS2 Python Interface initialization 
    node = SubscriberNode("topic_helloworld_sub")  #  establish ROS2 Node object and initialize 
    rclpy.spin(node)                               #  Loop waiting for ROS2 sign out 
    node.destroy_node()                            #  Destroy the node object 
    rclpy.shutdown()                               #  close ROS2 Python Interface 

After writing the code, you need to set the compilation options of the function package , Let the system know Python Program entry , To open a feature pack setup.py file , Add the following entry point configuration :

    entry_points={
    
        'console_scripts': [
         'topic_helloworld_pub  = learning_topic.topic_helloworld_pub:main',
         'topic_helloworld_sub  = learning_topic.topic_helloworld_sub:main',
        ],
    },

Process summary
Analyze the above procedures , If we want to implement a subscriber , The process is as follows :

Programming interface initialization
Create nodes and initialize
Create subscriber object
Callback function handles topic data
Destroy the node and close the interface

It can also be explained by machine vision , I'm just going to go over it here , You can watch the video of Gu Yue .

2. Topic command line operation

ros2 topic list                #  Check the list of topics 
ros2 topic info <topic_name>   #  View topic information 
ros2 topic hz <topic_name>     #  Check the frequency of topic Publishing 
ros2 topic bw <topic_name>     #  Check the topic transmission bandwidth 
ros2 topic echo <topic_name>   #  View topic data 
ros2 topic pub <topic_name> <msg_type> <msg_data>   #  Post topic news 

summary

The characteristic of topic communication is one-way transmission 、 asynchronous communication , Suitable for periodic data transmission , For a complex robot system , This feature certainly cannot meet all the needs of data transmission .

原网站

版权声明
本文为[Me and nano]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/186/202207050635157884.html