ROS topic communication custom msg to achieve sending and receiving (6) c++, python

content

Introduction to custom msg

Custom msg implementation

 Topic communication custom msg call (C++)

 vscode configuration

Implement the publisher

implement subscriber

 Python implementation

write publisher

 implement subscriber


Introduction to custom msg

In the ROS communication protocol, the data carrier is an important part. ROS encapsulates some native data types through std_msgs, such as: String, Int32, Int64, Char, Bool, Empty.... However, these data are generally only Contains a data field, the single structure means functional limitations.

When transmitting some complex data, such as: lidar information... std_msgs is not enough due to its poor descriptiveness. In this scenario, a custom message type msg can be used

msgs are just simple text files, each line has field type and field name, the field types that can be used are:

  • int8, int16, int32, int64 (or unsigned types: uint*)

  • float32, float64

  • string

  • time, duration

  • other msg files

  • variable-length array[] and fixed-length array[C]

A special type of Header may be used when using other people's msg files

There is also a special type in ROS: Header, the header contains timestamp and coordinate frame information commonly used in ROS. You will often see that the first line of the msg file has Header标头.

A custom msg is essentially a text file

Custom msg implementation

 Requirement: Create a custom message that contains the person's information: name, height, age, etc.

process:

  1. Create msg files in a fixed format
  2. Edit configuration file
  3. Compile to generate intermediate files that can be called by Python or C++

Create new folders and files in vscode

 

 add dependencies

 

 After this modification

will be imported when compiling

message_generation

message_runtime

 Then modify the CMakeLists

 In this way, build depend depends on the function package message_generation when compiling.

The use of find_package is that when compiling the plumbing_pub_sub function package, you must rely on the package inside

Remark

ctrl + /

The key combination can directly remove comments in vscode

 

 add message file

 Represents a compile-time dependency on the std_msgs package

Because the complex messages that make up msg are standard messages, std_msg is required

 The above find_pachage depends on the packages in catkin_package, and there are layers of dependencies

then compile

After compiling, intermediate files will be generated

 

 The following is the intermediate file generated by python, which is used if called

 Topic communication custom msg call (C++)

need:

Write a publish-subscribe implementation, requiring the publisher to publish a custom message at a frequency of 10HZ (10 times per second), and the subscriber to subscribe to the custom message and print out the content of the message.

analyze:

In the model implementation, the ROS master does not need to be implemented, and the connection establishment has been encapsulated. There are three key points to pay attention to:

  1. Publisher
  2. receiver
  3. data (custom message here)

 vscode configuration

In order to facilitate code prompts and avoid throwing exceptions by mistake, you need to configure vscode first, and configure the previously generated head file path into the includepath property of c_cpp_properties.json:

 get the path then copy

 

 Copy it in and change it to **

The advantage of doing this is that

Do not throw exceptions by mistake

Implement the publisher

then create a new file

 copy code

go here and change to ** 

 

Then modify the CMakeLists as before

 This is adding executable permission

 this is initialization

add dependencies

 The function of this is to prevent an error from being reported before compiling the cpp file before compiling the msg file

With this, there will be no errors caused by this reason, that is, errors in logic problems

Then compile the function package

Invoking"make cmake_check_build_system"failed

 The high probability of this error is that the file name or node name does not correspond to the cause.

My error is because the person here is wrong before

Did not look carefully at the reason for the error 

After the modification, the compilation was successful

Then open the terminal and create a new one

implement subscriber

 create a new file

The error is reported here because the include file has not been modified

no need to hurry

Copy the following code (make corresponding modifications to your own file name, etc.)

/*
    需求: 订阅人的信息

*/

#include "ros/ros.h"
#include "demo02_talker_listener/Person.h"

void doPerson(const demo02_talker_listener::Person::ConstPtr& person_p){
    ROS_INFO("订阅的人信息:%s, %d, %.2f", person_p->name.c_str(), person_p->age, person_p->height);
}

int main(int argc, char *argv[])
{   
    setlocale(LC_ALL,"");

    //1.初始化 ROS 节点
    ros::init(argc,argv,"listener_person");
    //2.创建 ROS 句柄
    ros::NodeHandle nh;
    //3.创建订阅对象
    ros::Subscriber sub = nh.subscribe<demo02_talker_listener::Person>("chatter_person",10,doPerson);

    //4.回调函数中处理 person

    //5.ros::spin();
    ros::spin();    
    return 0;
}

Corresponding changes to the configuration file

open terminal

 Open Computation Graph

 Python implementation

process:

  1. Write the publisher implementation;
  2. Write the subscriber implementation;
  3. Add executable permission to python file;
  4. edit configuration file;
  5. Compile and execute.

 

{
    "python.autoComplete.extraPaths": [
        "/opt/ros/noetic/lib/python3/dist-packages",
        "/xxx/yyy工作空间/devel/lib/python3/dist-packages"
    ]
}

 

 

 

 Complete vscode configuration

This is for the automatic completion function and does not affect the operation

write publisher

Then copy the following code

#! /usr/bin/env python
"""
    发布方:
        循环发送消息

"""
import rospy
from demo02_talker_listener.msg import Person


if __name__ == "__main__":
    #1.初始化 ROS 节点
    rospy.init_node("talker_person_p")
    #2.创建发布者对象
    pub = rospy.Publisher("chatter_person",Person,queue_size=10)
    #3.组织消息
    p = Person()
    p.name = "葫芦瓦"
    p.age = 18
    p.height = 0.75

    #4.编写消息发布逻辑
    rate = rospy.Rate(1)
    while not rospy.is_shutdown():
        pub.publish(p)  #发布消息
        rate.sleep()  #休眠
        rospy.loginfo("姓名:%s, 年龄:%d, 身高:%.2f",p.name, p.age, p.height)

Add execute permission after writing

 

Next, modify the CMakeLists configuration

 

 start terminal

 implement subscriber

 create a new file

copy code

#! /usr/bin/env python
"""
    订阅方:
        订阅消息

"""
import rospy
from demo02_talker_listener.msg import Person

def doPerson(p):
    rospy.loginfo("接收到的人的信息:%s, %d, %.2f",p.name, p.age, p.height)


if __name__ == "__main__":
    #1.初始化节点
    rospy.init_node("listener_person_p")
    #2.创建订阅者对象
    sub = rospy.Subscriber("chatter_person",Person,doPerson,queue_size=10)
    rospy.spin() #4.循环

Add execute permission

 

 Modify the CMakeLists configuration

Then open the terminal and run

 

 Finish

Remember here that python also needs source

This can only be compiled in bash or it will report an error

 Open Computation Graph

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324333123&siteId=291194637