example: Add mqtt5 example

This commit is contained in:
yuanjm 2022-03-03 15:41:43 +08:00 committed by BOT
parent 66e0171c42
commit 196831efa8
8 changed files with 467 additions and 0 deletions

View File

@ -0,0 +1,10 @@
# The following four lines of boilerplate have to be in your project's CMakeLists
# in this exact order for cmake to work correctly
cmake_minimum_required(VERSION 3.16)
# (Not part of the boilerplate)
# This example uses an extra component for common functions such as Wi-Fi and Ethernet connection.
set(EXTRA_COMPONENT_DIRS $ENV{IDF_PATH}/examples/common_components/protocol_examples_common)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
project(mqtt5)

View File

@ -0,0 +1,78 @@
| Supported Targets | ESP32 | ESP32-C3 | ESP32-S2 | ESP32-S3 |
| ----------------- | ----- | -------- | -------- | -------- |
# ESP-MQTT sample application
(See the README.md file in the upper level 'examples' directory for more information about examples.)
This example connects to the broker URI selected using `idf.py menuconfig` (using mqtt tcp transport) and as a demonstration subscribes/unsubscribes and send a message on certain topic.
(Please note that the public broker is maintained by the community so may not be always available, for details please see this [disclaimer](https://iot.eclipse.org/getting-started/#sandboxes))
Note: If the URI equals `FROM_STDIN` then the broker address is read from stdin upon application startup (used for testing)
It uses ESP-MQTT library which implements mqtt client to connect to mqtt broker with MQTT version 5.
The more details about MQTT v5, please refer to [official website](https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html)
## How to use example
### Hardware Required
This example can be executed on any ESP32 board, the only required interface is WiFi and connection to internet.
### Configure the project
* Open the project configuration menu (`idf.py menuconfig`)
* Configure Wi-Fi or Ethernet under "Example Connection Configuration" menu. See "Establishing Wi-Fi or Ethernet Connection" section in [examples/protocols/README.md](../../README.md) for more details.
* MQTT v5 protocol (`CONFIG_MQTT_PROTOCOL_5`) under "ESP-MQTT Configurations" menu is enabled by `sdkconfig.defaults`.
### Build and Flash
Build the project and flash it to the board, then run monitor tool to view serial output:
```
idf.py -p PORT flash monitor
```
(To exit the serial monitor, type ``Ctrl-]``.)
See the Getting Started Guide for full steps to configure and use ESP-IDF to build projects.
## Example Output
```
I (5119) esp_netif_handlers: example_connect: sta ip: 192.168.3.143, mask: 255.255.255.0, gw: 192.168.3.1
I (5119) example_connect: Got IPv4 event: Interface "example_connect: sta" address: 192.168.3.143
I (5619) example_connect: Got IPv6 event: Interface "example_connect: sta" address: fe80:0000:0000:0000:c64f:33ff:fe24:6645, type: ESP_IP6_ADDR_IS_LINK_LOCAL
I (5619) example_connect: Connected to example_connect: sta
I (5629) example_connect: - IPv4 address: 192.168.3.143
I (5629) example_connect: - IPv6 address: fe80:0000:0000:0000:c64f:33ff:fe24:6645, type: ESP_IP6_ADDR_IS_LINK_LOCAL
I (5649) MQTT5_EXAMPLE: Other event id:7
W (6299) wifi:<ba-add>idx:0 (ifx:0, 34:29:12:43:c5:40), tid:7, ssn:0, winSize:64
I (7439) MQTT5_EXAMPLE: MQTT_EVENT_CONNECTED
I (7439) MQTT5_EXAMPLE: sent publish successful, msg_id=53118
I (7439) MQTT5_EXAMPLE: sent subscribe successful, msg_id=41391
I (7439) MQTT5_EXAMPLE: sent subscribe successful, msg_id=13695
I (7449) MQTT5_EXAMPLE: sent unsubscribe successful, msg_id=55594
I (7649) mqtt5_client: MQTT_MSG_TYPE_PUBACK return code is -1
I (7649) MQTT5_EXAMPLE: MQTT_EVENT_PUBLISHED, msg_id=53118
I (8039) mqtt5_client: MQTT_MSG_TYPE_SUBACK return code is 0
I (8049) MQTT5_EXAMPLE: MQTT_EVENT_SUBSCRIBED, msg_id=41391
I (8049) MQTT5_EXAMPLE: sent publish successful, msg_id=0
I (8059) mqtt5_client: MQTT_MSG_TYPE_SUBACK return code is 2
I (8059) MQTT5_EXAMPLE: MQTT_EVENT_SUBSCRIBED, msg_id=13695
I (8069) MQTT5_EXAMPLE: sent publish successful, msg_id=0
I (8079) MQTT5_EXAMPLE: MQTT_EVENT_DATA
I (8079) MQTT5_EXAMPLE: key is board, value is esp32
I (8079) MQTT5_EXAMPLE: key is u, value is user
I (8089) MQTT5_EXAMPLE: key is p, value is password
I (8089) MQTT5_EXAMPLE: payload_format_indicator is 1
I (8099) MQTT5_EXAMPLE: response_topic is /topic/test/response
I (8109) MQTT5_EXAMPLE: correlation_data is 123456
I (8109) MQTT5_EXAMPLE: content_type is
I (8119) MQTT5_EXAMPLE: TOPIC=/topic/qos1
I (8119) MQTT5_EXAMPLE: DATA=data_3
I (8129) mqtt5_client: MQTT_MSG_TYPE_UNSUBACK return code is 0
I (8129) MQTT5_EXAMPLE: MQTT_EVENT_UNSUBSCRIBED, msg_id=55594
I (8139) mqtt_client: Client asked to disconnect
I (9159) MQTT5_EXAMPLE: MQTT_EVENT_DISCONNECTED
```

View File

@ -0,0 +1,2 @@
idf_component_register(SRCS "app_main.c"
INCLUDE_DIRS ".")

View File

@ -0,0 +1,13 @@
menu "Example Configuration"
config BROKER_URL
string "Broker URL"
default "mqtt://mqtt.eclipseprojects.io"
help
URL of the broker to connect to
config BROKER_URL_FROM_STDIN
bool
default y if BROKER_URL = "FROM_STDIN"
endmenu

View File

@ -0,0 +1,289 @@
/*
* SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>
#include "esp_system.h"
#include "nvs_flash.h"
#include "esp_event.h"
#include "esp_netif.h"
#include "protocol_examples_common.h"
#include "esp_log.h"
#include "mqtt_client.h"
static const char *TAG = "MQTT5_EXAMPLE";
static void log_error_if_nonzero(const char *message, int error_code)
{
if (error_code != 0) {
ESP_LOGE(TAG, "Last error %s: 0x%x", message, error_code);
}
}
static esp_mqtt5_user_property_item_t user_property_arr[] = {
{"board", "esp32"},
{"u", "user"},
{"p", "password"}
};
#define USE_PROPERTY_ARR_SIZE sizeof(user_property_arr)/sizeof(esp_mqtt5_user_property_item_t)
static esp_mqtt5_publish_property_config_t publish_property = {
.payload_format_indicator = 1,
.message_expiry_interval = 1000,
.topic_alias = 0,
.response_topic = "/topic/test/response",
.correlation_data = "123456",
.correlation_data_len = 6,
};
static esp_mqtt5_subscribe_property_config_t subscribe_property = {
.subscribe_id = 25555,
.no_local_flag = false,
.retain_as_published_flag = false,
.retain_handle = 0,
.is_share_subscribe = true,
.share_name = "group1",
};
static esp_mqtt5_subscribe_property_config_t subscribe1_property = {
.subscribe_id = 25555,
.no_local_flag = true,
.retain_as_published_flag = false,
.retain_handle = 0,
};
static esp_mqtt5_unsubscribe_property_config_t unsubscribe_property = {
.is_share_subscribe = true,
.share_name = "group1",
};
static esp_mqtt5_disconnect_property_config_t disconnect_property = {
.session_expiry_interval = 60,
.disconnect_reason = 0,
};
static void print_user_property(mqtt5_user_property_handle_t user_property)
{
if (user_property) {
uint8_t count = esp_mqtt5_client_get_user_property_count(user_property);
if (count) {
esp_mqtt5_user_property_item_t *item = malloc(count * sizeof(esp_mqtt5_user_property_item_t));
if (esp_mqtt5_client_get_user_property(user_property, item, &count) == ESP_OK) {
for (int i = 0; i < count; i ++) {
esp_mqtt5_user_property_item_t *t = &item[i];
ESP_LOGI(TAG, "key is %s, value is %s", t->key, t->value);
free((char *)t->key);
free((char *)t->value);
}
}
free(item);
}
}
}
/*
* @brief Event handler registered to receive MQTT events
*
* This function is called by the MQTT client event loop.
*
* @param handler_args user data registered to the event.
* @param base Event base for the handler(always MQTT Base in this example).
* @param event_id The id for the received event.
* @param event_data The data for the event, esp_mqtt_event_handle_t.
*/
static void mqtt5_event_handler(void *handler_args, esp_event_base_t base, int32_t event_id, void *event_data)
{
ESP_LOGD(TAG, "Event dispatched from event loop base=%s, event_id=%d", base, event_id);
esp_mqtt_event_handle_t event = event_data;
esp_mqtt_client_handle_t client = event->client;
int msg_id;
ESP_LOGD(TAG, "free heap size is %d, maxminu %d", esp_get_free_heap_size(), esp_get_minimum_free_heap_size());
switch ((esp_mqtt_event_id_t)event_id) {
case MQTT_EVENT_CONNECTED:
ESP_LOGI(TAG, "MQTT_EVENT_CONNECTED");
print_user_property(event->property->user_property);
esp_mqtt5_client_set_user_property(&publish_property.user_property, user_property_arr, USE_PROPERTY_ARR_SIZE);
esp_mqtt5_client_set_publish_property(client, &publish_property);
msg_id = esp_mqtt_client_publish(client, "/topic/qos1", "data_3", 0, 1, 1);
esp_mqtt5_client_delete_user_property(publish_property.user_property);
publish_property.user_property = NULL;
ESP_LOGI(TAG, "sent publish successful, msg_id=%d", msg_id);
esp_mqtt5_client_set_user_property(&subscribe_property.user_property, user_property_arr, USE_PROPERTY_ARR_SIZE);
esp_mqtt5_client_set_subscribe_property(client, &subscribe_property);
msg_id = esp_mqtt_client_subscribe(client, "/topic/qos0", 0);
esp_mqtt5_client_delete_user_property(subscribe_property.user_property);
subscribe_property.user_property = NULL;
ESP_LOGI(TAG, "sent subscribe successful, msg_id=%d", msg_id);
esp_mqtt5_client_set_user_property(&subscribe1_property.user_property, user_property_arr, USE_PROPERTY_ARR_SIZE);
esp_mqtt5_client_set_subscribe_property(client, &subscribe1_property);
msg_id = esp_mqtt_client_subscribe(client, "/topic/qos1", 2);
esp_mqtt5_client_delete_user_property(subscribe1_property.user_property);
subscribe1_property.user_property = NULL;
ESP_LOGI(TAG, "sent subscribe successful, msg_id=%d", msg_id);
esp_mqtt5_client_set_user_property(&unsubscribe_property.user_property, user_property_arr, USE_PROPERTY_ARR_SIZE);
esp_mqtt5_client_set_unsubscribe_property(client, &unsubscribe_property);
msg_id = esp_mqtt_client_unsubscribe(client, "/topic/qos0");
ESP_LOGI(TAG, "sent unsubscribe successful, msg_id=%d", msg_id);
esp_mqtt5_client_delete_user_property(unsubscribe_property.user_property);
unsubscribe_property.user_property = NULL;
break;
case MQTT_EVENT_DISCONNECTED:
ESP_LOGI(TAG, "MQTT_EVENT_DISCONNECTED");
print_user_property(event->property->user_property);
break;
case MQTT_EVENT_SUBSCRIBED:
ESP_LOGI(TAG, "MQTT_EVENT_SUBSCRIBED, msg_id=%d", event->msg_id);
print_user_property(event->property->user_property);
esp_mqtt5_client_set_publish_property(client, &publish_property);
msg_id = esp_mqtt_client_publish(client, "/topic/qos0", "data", 0, 0, 0);
ESP_LOGI(TAG, "sent publish successful, msg_id=%d", msg_id);
break;
case MQTT_EVENT_UNSUBSCRIBED:
ESP_LOGI(TAG, "MQTT_EVENT_UNSUBSCRIBED, msg_id=%d", event->msg_id);
print_user_property(event->property->user_property);
esp_mqtt5_client_set_user_property(&disconnect_property.user_property, user_property_arr, USE_PROPERTY_ARR_SIZE);
esp_mqtt5_client_set_disconnect_property(client, &disconnect_property);
esp_mqtt5_client_delete_user_property(disconnect_property.user_property);
disconnect_property.user_property = NULL;
esp_mqtt_client_disconnect(client);
break;
case MQTT_EVENT_PUBLISHED:
ESP_LOGI(TAG, "MQTT_EVENT_PUBLISHED, msg_id=%d", event->msg_id);
print_user_property(event->property->user_property);
break;
case MQTT_EVENT_DATA:
ESP_LOGI(TAG, "MQTT_EVENT_DATA");
print_user_property(event->property->user_property);
ESP_LOGI(TAG, "payload_format_indicator is %d", event->property->payload_format_indicator);
ESP_LOGI(TAG, "response_topic is %.*s", event->property->response_topic_len, event->property->response_topic);
ESP_LOGI(TAG, "correlation_data is %.*s", event->property->correlation_data_len, event->property->correlation_data);
ESP_LOGI(TAG, "content_type is %.*s", event->property->content_type_len, event->property->content_type);
ESP_LOGI(TAG, "TOPIC=%.*s", event->topic_len, event->topic);
ESP_LOGI(TAG, "DATA=%.*s", event->data_len, event->data);
break;
case MQTT_EVENT_ERROR:
ESP_LOGI(TAG, "MQTT_EVENT_ERROR");
print_user_property(event->property->user_property);
ESP_LOGI(TAG, "MQTT5 return code is %d", event->error_handle->connect_return_code);
if (event->error_handle->error_type == MQTT_ERROR_TYPE_TCP_TRANSPORT) {
log_error_if_nonzero("reported from esp-tls", event->error_handle->esp_tls_last_esp_err);
log_error_if_nonzero("reported from tls stack", event->error_handle->esp_tls_stack_err);
log_error_if_nonzero("captured as transport's socket errno", event->error_handle->esp_transport_sock_errno);
ESP_LOGI(TAG, "Last errno string (%s)", strerror(event->error_handle->esp_transport_sock_errno));
}
break;
default:
ESP_LOGI(TAG, "Other event id:%d", event->event_id);
break;
}
}
static void mqtt5_app_start(void)
{
esp_mqtt5_connection_property_config_t connect_property = {
.session_expiry_interval = 10,
.maximum_packet_size = 1024,
.receive_maximum = 65535,
.topic_alias_maximum = 2,
.request_resp_info = true,
.request_problem_info = true,
.will_delay_interval = 10,
.payload_format_indicator = true,
.message_expiry_interval = 10,
.response_topic = "/test/response",
.correlation_data = "123456",
.correlation_data_len = 6,
};
esp_mqtt_client_config_t mqtt5_cfg = {
.broker.address.uri = CONFIG_BROKER_URL,
.session.protocol_ver = MQTT_PROTOCOL_V_5,
.network.disable_auto_reconnect = true,
.credentials.username = "123",
.credentials.authentication.password = "456",
.session.last_will.topic = "/topic/will",
.session.last_will.msg = "i will leave",
.session.last_will.msg_len = 12,
.session.last_will.qos = 1,
.session.last_will.retain = true,
};
#if CONFIG_BROKER_URL_FROM_STDIN
char line[128];
if (strcmp(mqtt5_cfg.uri, "FROM_STDIN") == 0) {
int count = 0;
printf("Please enter url of mqtt broker\n");
while (count < 128) {
int c = fgetc(stdin);
if (c == '\n') {
line[count] = '\0';
break;
} else if (c > 0 && c < 127) {
line[count] = c;
++count;
}
vTaskDelay(10 / portTICK_PERIOD_MS);
}
mqtt5_cfg.broker.address.uri = line;
printf("Broker url: %s\n", line);
} else {
ESP_LOGE(TAG, "Configuration mismatch: wrong broker url");
abort();
}
#endif /* CONFIG_BROKER_URL_FROM_STDIN */
esp_mqtt_client_handle_t client = esp_mqtt_client_init(&mqtt5_cfg);
/* Set connection properties and user properties */
esp_mqtt5_client_set_user_property(&connect_property.user_property, user_property_arr, USE_PROPERTY_ARR_SIZE);
esp_mqtt5_client_set_user_property(&connect_property.will_user_property, user_property_arr, USE_PROPERTY_ARR_SIZE);
esp_mqtt5_client_set_connect_property(client, &connect_property);
/* If you call esp_mqtt5_client_set_user_property to set user properties, DO NOT forget to delete them.
* esp_mqtt5_client_set_connect_property will malloc buffer to store the user_property and you can delete it after
*/
esp_mqtt5_client_delete_user_property(connect_property.user_property);
esp_mqtt5_client_delete_user_property(connect_property.will_user_property);
/* The last argument may be used to pass data to the event handler, in this example mqtt_event_handler */
esp_mqtt_client_register_event(client, ESP_EVENT_ANY_ID, mqtt5_event_handler, NULL);
esp_mqtt_client_start(client);
}
void app_main(void)
{
ESP_LOGI(TAG, "[APP] Startup..");
ESP_LOGI(TAG, "[APP] Free memory: %d bytes", esp_get_free_heap_size());
ESP_LOGI(TAG, "[APP] IDF version: %s", esp_get_idf_version());
esp_log_level_set("*", ESP_LOG_INFO);
esp_log_level_set("MQTT_CLIENT", ESP_LOG_VERBOSE);
esp_log_level_set("MQTT_EXAMPLE", ESP_LOG_VERBOSE);
esp_log_level_set("TRANSPORT_BASE", ESP_LOG_VERBOSE);
esp_log_level_set("esp-tls", ESP_LOG_VERBOSE);
esp_log_level_set("TRANSPORT", ESP_LOG_VERBOSE);
esp_log_level_set("OUTBOX", ESP_LOG_VERBOSE);
ESP_ERROR_CHECK(nvs_flash_init());
ESP_ERROR_CHECK(esp_netif_init());
ESP_ERROR_CHECK(esp_event_loop_create_default());
/* This helper function configures Wi-Fi or Ethernet, as selected in menuconfig.
* Read "Establishing Wi-Fi or Ethernet Connection" section in
* examples/protocols/README.md for more information about this function.
*/
ESP_ERROR_CHECK(example_connect());
mqtt5_app_start();
}

View File

@ -0,0 +1,65 @@
#!/usr/bin/env python
#
# SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD
# SPDX-License-Identifier: Apache-2.0
import logging
import os
import pytest
from pytest_embedded import Dut
@pytest.mark.esp32
@pytest.mark.ethernet
def test_examples_protocol_mqtt5(dut: Dut) -> None:
"""
steps: |
1. join AP
2. connect to mqtt://mqtt.eclipseprojects.io
3. check conneciton success
"""
# check and log bin size
binary_file = os.path.join(dut.app.binary_path, 'mqtt5.bin')
bin_size = os.path.getsize(binary_file)
logging.info('mqtt5_bin_size : {}KB'.format(bin_size // 1024))
# check if connected or not
dut.expect_exact('MQTT_EVENT_CONNECTED', timeout=30)
# check log
res = dut.expect(r'sent publish successful, msg_id=(\d+)')
msgid_pub1 = res.group(1).decode('utf8')
res = dut.expect(r'sent subscribe successful, msg_id=(\d+)')
msgid_sub1 = res.group(1).decode('utf8')
res = dut.expect(r'sent subscribe successful, msg_id=(\d+)')
msgid_sub2 = res.group(1).decode('utf8')
res = dut.expect(r'sent unsubscribe successful, msg_id=(\d+)')
msgid_unsub = res.group(1).decode('utf8')
res = dut.expect(r'MQTT_EVENT_PUBLISHED, msg_id=(\d+)')
msgid_pubd = res.group(1).decode('utf8')
assert msgid_pubd == msgid_pub1
res = dut.expect(r'MQTT_EVENT_SUBSCRIBED, msg_id=(\d+)')
msgid_subd = res.group(1).decode('utf8')
assert msgid_subd == msgid_sub1
dut.expect_exact('sent publish successful, msg_id=0')
res = dut.expect(r'MQTT_EVENT_SUBSCRIBED, msg_id=(\d+)')
msgid_subd = res.group(1).decode('utf8')
assert msgid_subd == msgid_sub2
dut.expect_exact('sent publish successful, msg_id=0')
dut.expect_exact('MQTT_EVENT_DATA')
dut.expect_exact('key is board, value is esp32')
dut.expect_exact('key is u, value is user')
dut.expect_exact('key is p, value is password')
dut.expect_exact('payload_format_indicator is 1')
dut.expect_exact('response_topic is /topic/test/response')
dut.expect_exact('correlation_data is 123456')
dut.expect_exact('TOPIC=/topic/qos1')
dut.expect_exact('DATA=data_3')
res = dut.expect(r'MQTT_EVENT_UNSUBSCRIBED, msg_id=(\d+)')
msgid_unsubd = res.group(1).decode('utf8')
assert msgid_unsubd == msgid_unsub
dut.expect_exact('MQTT_EVENT_DISCONNECTED')
logging.info('MQTT5 pytest pass')

View File

@ -0,0 +1,9 @@
CONFIG_EXAMPLE_CONNECT_ETHERNET=y
CONFIG_EXAMPLE_CONNECT_WIFI=n
CONFIG_EXAMPLE_USE_INTERNAL_ETHERNET=y
CONFIG_EXAMPLE_ETH_PHY_IP101=y
CONFIG_EXAMPLE_ETH_MDC_GPIO=23
CONFIG_EXAMPLE_ETH_MDIO_GPIO=18
CONFIG_EXAMPLE_ETH_PHY_RST_GPIO=5
CONFIG_EXAMPLE_ETH_PHY_ADDR=1
CONFIG_MQTT_PROTOCOL_5=y

View File

@ -0,0 +1 @@
CONFIG_MQTT_PROTOCOL_5=y