ESP32-C3 Getting Started Tutorial Network Chapter (3. Basic introduction and test of MQTT protocol)

在前面,我们已经学会了 ESP32-C3 的WiFi 配置以及使用,为我们学习网络协议建立了基础。
这篇文章我们就来学习测试一下ESP32-C3 的 MQTT 驱动。

foreword

The following ESP32-C3 functional tests are based on the development board designed by ourselves:

Draw a development board of ESP32-C3 by yourself (the first time to use Lichuang EDA) (PCB is available)

The development environment is Espressif's official ESP-IDF, built based on the VScode plugin:

ESP32-C3 VScode development environment is built (based on Espressif's official ESP-IDF - Windows and Ubuntu dual environment)

Learn to use the MQTT protocol package of ESP32-C3, do not use other peripherals.

1. Basic introduction

1.1 Basic Concepts of MQTT Protocol

There are many basic concepts on the Internet. The basic concepts are extracted from the Internet to make an explanation. The explanation is excerpted from Baidu Encyclopedia and the following blog posts:

MQTT Baidu Encyclopedia

MQTT – Getting Started

MQTT (Message Queuing Telemetry Transport) is a messaging protocol based on the publish/subscribe paradigm under the ISO standard (ISO/IEC PRF 20922). It works on the TCP/IP protocol suite and is a publish/subscribe message protocol designed for remote devices with low hardware performance and poor network conditions. For this, it needs a message middleware.

MQTT is a client-server based message publish/subscribe transport protocol. The MQTT protocol is lightweight, simple, open and easy to implement, which makes it applicable to a wide range of applications. In many cases, including constrained environments, such as: Machine-to-Machine (M2M) communication and the Internet of Things (IoT). It is widely used in communicating sensors via satellite links, occasional dial-up medical devices, smart homes, and some miniaturized devices.

The communication model of MQTT is as follows:
insert image description here
MQTT protocol features:

  1. Use the publish/subscribe message model to provide one-to-many message publishing and decouple applications;
  2. Message transmission masked to payload content;
  3. provide network connectivity using TCP/IP;
  4. There are three message publishing qualities of service:
    "at most once", message publishing is completely dependent on the underlying TCP/IP network. Message loss or duplication can occur. This level can be used in the case of environmental sensor data, it doesn't matter if one read record is lost, because there will be a second transmission soon. This method is mainly for the push of ordinary APP. If your smart device is not connected to the Internet when the message is pushed, and the push has not been received in the past, it will not be received when it is connected to the Internet again.
    "At least once" ensures that messages arrive, but message duplication may occur.
    "Only Once" ensures that the message arrives once. This level can be used in some more demanding billing systems. In billing systems, duplicate or lost messages can lead to incorrect results. This highest-quality message publishing service can also be used to push instant messaging apps to ensure that users receive and only receive it once.
  5. Small transfers with little overhead (fixed-length headers are 2 bytes), and protocol switching is minimized to reduce network traffic;
  6. A mechanism for notifying interested parties of a client abort using the Last Will and Testament features.
    Last Will: The last word mechanism, used to notify other devices under the same topic that the device that sent the last words has been disconnected. Testament: The testament mechanism, similar in function to Last Will.

MQTT protocol implementation method:

Implementing the MQTT protocol requires communication between the client and the server. During the communication process, there are three identities in the MQTT protocol: publisher (Publish), broker (Broker) (server), and subscriber (Subscribe). The publisher and subscriber of the message are both clients, the message broker is the server, and the message publisher can be a subscriber at the same time.

The message transmitted by MQTT is divided into two parts: topic (Topic) and payload (payload):

  1. Topic can be understood as the type of message. After the subscriber subscribes (Subscribe), he will receive the message content (payload) of the topic;
  2. The payload, which can be understood as the content of the message, refers to the specific content to be used by the subscriber.

insert image description here

1.2 ESP-MQTT Basics

Regarding the MQTT of ESP32-C3, the official link is as follows: ESP-MQTT official description

The bottom layer corresponding to ESP-MQTT has been written, and the official also mainly introduces what MQTT-based applications are:
insert image description here

1.2.1 SSL

SSL Baidu Encyclopedia

SSL (Secure Sockets Layer), and its successor, Transport Layer Security (TLS), is a security . TLS and SSL encrypt network connections at the transport layer. Most Internet logins use SSL/TLS.

In the official sample code, the MQTT example of SSL transmission is as follows:
insert image description here

1.2.2 MQTT over Websocket

MQTT over WebSocket wraps the MQTT control message into a WebSocket package and sends it through the WebSocket pipeline. That is to use WebSocket to support the connection between MQTT Client and Broker.

What they have in common:

  • MQTT and WebSocket are the current bottom layer of application layer protocols
  • Both use the TCP protocol to ensure reliable transmission of data
  • Both define their own message (message) structure
  • Both support two-way communication and use binary encoding (different from HTTP, which is based on text encoding)
  • Both are open standard mqtt rfc6455

Difference between them:

  • WebSocket is a simple message protocol that focuses on solving the problem that the browser and the server cannot communicate in both directions. Essentially a bit like the UDP protocol on top of the TCP protocol. WebSocket only defines how the session is initiated and the format and type of the message. How messaging is used is entirely controlled by the application.
  • MQTT is a relatively complex message delivery protocol, while WebSocket only implements simple message communication on top of the TCP protocol. The two protocols work at different levels. In this sense, MQTT can work on top of WebSocket.
  • MQTT is used for communication between native devices, and MQTT over WebSocket is mainly used for communication between MQTT devices and the web.

In the official example, the example of MQTT over Websocket is as follows:
insert image description here

2. Example test

In the previous introduction to the basics of ESP3-MQTT, we learned about the types of official MQTT examples. Today, as the basic test, the selected example code is ../mqtt/tcp:
insert image description here

2.1 Test Tools

This test uses an online public MQTT server. For references related to public online servers, you can check the following articles:

An article to understand the mainstream online public MQTT server

Our ESP32-C3 development board is used as a client, and our PC is used as another client;

The MQTT X tool can be used on a PC:

MQTT X tool download address

insert image description here
After downloading the MQTT X tool, let's establish a connection (you don't need to check the basic test SSL):
MQTT connection settings
after setting the above, remember Usenameand Password, and click connect.

2.2 Brief analysis of sample code

An introductory tutorial, get started quickly, our introduction from the beginning of the article does not involve the specific implementation and protocol format of the MQTT protocol. Here our purpose is to correctly grasp the use of ESP3-MQTT and to use it quickly in general projects.

So the sample code, briefly introduce the functions of each part, we start from the app_mainbeginning , then there is a ESP_ERROR_CHECK(example_connect());function at the beginning of the program to connect to wifi, which needs to menuconfigbe configured in , but we are using the Vscode plugin, so Just click the settings icon:
The corresponding settings of menuconfig in the plugin

Find the corresponding wifi settings, and fill in the ssid and Password as shown below:
example_connect() corresponding settings

mqtt_app_start(void)

At app_mainthe end of the static void mqtt_app_start(void)function . In this function, it needs to be filled in according to the settings in the MQTT X tool:

Note that there is a Client ID option in the figure below, the ID of the client. If you want the PC and the ESP32 development board to be different clients, the two IDs cannot be the same. If it is in the figure below, the server will think that they are two clients. Therefore, in the actual test, you need to pay attention to the fact that the Client IDs are not the same, so as two independent clients, you can do mutual publishing and subscription testing.

mqtt_cfg configuration

mqtt_event_handler_cb(esp_mqtt_event_handle_t event)

clientAfter the above is started , all events are processed in the callback function, the callback function registered above is mqtt_event_handler, and this function calls the mqtt_event_handler_cb()function:

Analysis of mqtt_event_handler_cb

2.3 Testing

After understanding the sample code, after modifying the mqtt_cfg configuration parameters and wifi connection parameters in the code, you can burn the program to the board. The effect of running after power on is as follows:
insert image description here
On the PC client MQTT X tool, we also subscribe to and For the same two topics in the example, the operation is as follows:

insert image description hereinsert image description here

After the MQTT X tool is set up, restart the development notebook, and you can receive 3 messages, as shown below:
insert image description here

As expected, then we know that in the sample program, /topic/qos1the subscription is cancelled at the end, and only the subscription is subscribed /topic/qos0, so we can publish the message of the topic through the PC client, and /topic/qos0perform the following operations in the MQTT X tool:
insert image description here
The final test renderings as follows:
insert image description here

Well, for the sample program, the test is basically over here.

Then combined with our previous study, we will implement a small application in the next article, using ESP32-C3 to connect to Alibaba Cloud using MQTT, reporting sensor data to the platform, and the platform issuing commands to control the development board.

Guess you like

Origin blog.csdn.net/weixin_42328389/article/details/123049977