ROS topic communication realizes release and reception (5) C++ version

In ROS, each function point is a separate process, and each process runs independently

ROS is a distributed framework for processes (also known as Nodes ). Because these processes can even be distributed on different hosts, and different hosts work together, thereby distributing the computing pressure.

But there is also a question: how do different processes communicate (how do data exchange between different processes)? This is the communication mechanism in ROS.

ROS 中的基本通信机制主要有如下三种实现策略:

话题通信(发布订阅模式)

服务通信(请求响应模式)

参数服务器(参数共享模式)

Topic communication is the most frequently used communication mode in ROS. Topic communication is based on the publish-subscribe mode, that is, one node publishes a message, and another node subscribes to the message

机器人在执行导航功能,使用的传感器是激光雷达,
机器人会采集激光雷达感知到的信息并计算,
然后生成运动控制信息驱动机器人底盘运动。

In the above scenario, topic communication is used more than once.

  • Taking the collection and processing of lidar information as an example, there is a node in ROS that needs to publish the data collected by the current radar from time to time, and there are nodes in the navigation module that subscribe and parse the radar data.
  • Taking the release of motion information as an example, the navigation module will calculate the motion control information from time to time based on the data collected by the sensor and publish it to the chassis. The chassis can also have a node that subscribes to the motion information and finally converts it into a pulse signal to control the motor.

Summary: It is the publisher who sends the signal, and the subscriber who receives the signal

By analogy, the collection of sensor data such as radar, camera, GPS, etc. also uses topic communication. In other words, topic communication is suitable for application scenarios related to continuously updated data transmission.

content

 theoretical model

 Topic Communication Basic Operation A (C++)

1. Write the publisher implementation first

2. Subscriber implementation


 theoretical model

 

 Topic Communication Basic Operation A (C++)

 

 The process is actually

1. Write the publisher implementation first

Create a workspace first

 

 Then

code .

 open vscode

{
// 有关 tasks.json 格式的文档,请参见
    // https://go.microsoft.com/fwlink/?LinkId=733558
    "version": "2.0.0",
    "tasks": [
        {
            "label": "catkin_make:debug", //代表提示的描述性信息
            "type": "shell",  //可以选择shell或者process,如果是shell代码是在shell里面运行一个命令,如果是process代表作为一个进程来运行
            "command": "catkin_make",//这个是我们需要运行的命令
            "args": [],//如果需要在命令后面加一些后缀,可以写在这里,比如-DCATKIN_WHITELIST_PACKAGES=“pac1;pac2”
            "group": {"kind":"build","isDefault":true},
            "presentation": {
                "reveal": "always"//可选always或者silence,代表是否输出信息
            },
            "problemMatcher": "$msCompile"
        }
    ]
}

 

Create the initial package

 then create a new file

then write the code

/*
    需求: 实现基本的话题通信,一方发布数据,一方接收数据,
         实现的关键点:
         1.发送方
         2.接收方
         3.数据(此处为普通文本)

         PS: 二者需要设置相同的话题


    消息发布方:
        循环发布信息:HelloWorld 后缀数字编号

    实现流程:
        1.包含头文件 
        2.初始化 ROS 节点:命名(唯一)
        3.实例化 ROS 句柄
        4.实例化 发布者 对象
        5.组织被发布的数据,并编写逻辑发布数据

*/
// 1.包含头文件 
#include "ros/ros.h"
#include "std_msgs/String.h" //普通文本类型的消息
#include <sstream>

int main(int argc, char  *argv[])
{   
    //设置编码
    setlocale(LC_ALL,"");

    //2.初始化 ROS 节点:命名(唯一)
    // 参数1和参数2 后期为节点传值会使用
    // 参数3 是节点名称,是一个标识符,需要保证运行后,在 ROS 网络拓扑中唯一
    ros::init(argc,argv,"talker");
    //3.实例化 ROS 句柄
    ros::NodeHandle nh;//该类封装了 ROS 中的一些常用功能

    //4.实例化 发布者 对象
    //泛型: 发布的消息类型
    //参数1: 要发布到的话题
    //参数2: 队列中最大保存的消息数,超出此阀值时,先进的先销毁(时间早的先销毁)
    ros::Publisher pub = nh.advertise<std_msgs::String>("chatter",10);

    //5.组织被发布的数据,并编写逻辑发布数据
    //数据(动态组织)
    std_msgs::String msg;
    // msg.data = "你好啊!!!";
    std::string msg_front = "Hello 你好!"; //消息前缀
    int count = 0; //消息计数器

    //逻辑(一秒10次)
    ros::Rate r(1);

    //节点不死
    while (ros::ok())
    {
        //使用 stringstream 拼接字符串与编号
        std::stringstream ss;
        ss << msg_front << count;
        msg.data = ss.str();
        //发布消息
        pub.publish(msg);
        //加入调试,打印发送的消息
        ROS_INFO("发送的消息:%s",msg.data.c_str());

        //根据前面制定的发送贫频率自动休眠 休眠时间 = 1/频率;
        r.sleep();
        count++;//循环结束前,让 count 自增
        //暂无应用
        ros::spinOnce();
    }


    return 0;
}

Then configure cmakelist.txt

 Generally use the file name as the node name

 Change to the node name named above

 After the change, ctrl shift b and compile it

Then open a terminal on the desktop and open roscore

Then open another terminal

 Remark:

[rosrun] Couldn't find executable named demo01_pub below /home/david/demo03_ws/src/plumbing_pub_sub

If this error occurs, it should be that the above compilation is not selected correctly

To select catkin_make:build this compilation task and then modify its json file accordingly

2. Subscriber implementation

 create a new file

 Then split the screen and click the book-like button on the right

 Then copy the subscriber code into it

/*
    需求: 实现基本的话题通信,一方发布数据,一方接收数据,
         实现的关键点:
         1.发送方
         2.接收方
         3.数据(此处为普通文本)


    消息订阅方:
        订阅话题并打印接收到的消息

    实现流程:
        1.包含头文件 
        2.初始化 ROS 节点:命名(唯一)
        3.实例化 ROS 句柄
        4.实例化 订阅者 对象
        5.处理订阅的消息(回调函数)
        6.设置循环调用回调函数

*/
// 1.包含头文件 
#include "ros/ros.h"
#include "std_msgs/String.h"

void doMsg(const std_msgs::String::ConstPtr& msg_p){
    ROS_INFO("我听见:%s",msg_p->data.c_str());
    // ROS_INFO("我听见:%s",(*msg_p).data.c_str());
}
int main(int argc, char  *argv[])
{
    setlocale(LC_ALL,"");
    //2.初始化 ROS 节点:命名(唯一)
    ros::init(argc,argv,"listener");
    //3.实例化 ROS 句柄
    ros::NodeHandle nh;

    //4.实例化 订阅者 对象
    ros::Subscriber sub = nh.subscribe<std_msgs::String>("chatter",10,doMsg);
    //5.处理订阅的消息(回调函数)

    //     6.设置循环调用回调函数
    ros::spin();//循环读取接收的数据,并调用回调函数处理

    return 0;
}

Then modify the file cmakelist.txt

 

 Then ctrl shift b compile it

 Then

open three terminals

first roscore

the second

 third subscriber

message received successfully

Remark 

 Remember to recompile every time you modify the code

#include "ros/ros.h"

When importing the package, the error is displayed, so don't worry about it, this is because there is no compilation.

 

Start Computational Graph

 

Guess you like

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