ESP32基础应用之使用mqtt连接阿里云物联网平台

Posted while(1)

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ESP32基础应用之使用mqtt连接阿里云物联网平台相关的知识,希望对你有一定的参考价值。

1 前言

本章实验实现:

  1. ESP32连接阿里云物联网平台并实现相互通信;
  2. ESP32上电后间隔2秒发送一次数据到阿里云,累计6次后停止发送;

2 在阿里云物联网平台新建ESP32设备

  1. 在阿里云物联网平台新建ESP32设备步骤,请参考:阿里云物联网平台创建产品与设备

3 ESP32工程

3.1 新建ESP32工程

  1. 选择 app-wifi-station 作为基础工程,并更改工程名为 app-MqttToAliyun
  2. 参考官方例程 examples\\protocols\\mqtt\\tcp
  3. 将官方例程相关文件复制到 app-MqttToAliyun 工程中,在此基础上修改

3.2 阿里云物联网平台ESP32设备相关证书

  1. 想要连接阿里云物联网平台我们需要阿里云如下参数
    ProductKey、DeviceName、DeviceSecret、Region、ClientID
  2. 打开阿里云物联网平台新建的ESP32设备页面
    在这里插入图片描述从上图中我们可以得到如下信息:
/*由阿里网平台可得如下信息*/
// ProductKey:"a1tUbQR2faQ"; 
// DeviceName:"dev-esp32"; 
// DeviceSecret:"e624520f169c755e0d02cd0ca99c94c1";
// Region:"cn-shanghai";     
  

最后我们自定义ClientID

// ClientID:="112233";  

3.3 将ESP32设备相关证书转换为程序中mqtt配置参数

/*Broker Address(host):${YourProductKey}.iot-as-mqtt.${YourRegionId}.aliyuncs.com*/
#define   Aliyun_host       "a1tUbQR2faQ.iot-as-mqtt.cn-shanghai.aliyuncs.com"
#define   Aliyun_port       1883  /*固定*/
/*Client ID:     ${ClientID}|securemode=${Mode},signmethod=${SignMethod}|*/
#define   Aliyun_client_id  "112233|securemode=2,signmethod=hmacsha1|"
/*User Name:     ${DeviceName}&${ProductKey}*/
#define   Aliyun_username   "dev-esp32&a1tUbQR2faQ"
/*使用官网 MQTT_Password 工具生成*/
#define   Aliyun_password   "9ABE732ED28BC38EEE7336FA824C26E744413360"
  1. Address(host)、port、client_id详细配置过程请参考官方说明:使用MQTT.fx接入物联网平台
    在这里插入图片描述
  2. username、password详细配置过程请参考官方说明:使用MQTT.fx接入物联网平台
    在这里插入图片描述

3.4 ESP32工程主要代码

mqtt相关函数详细操作请参考:乐鑫官方说明

/* MQTT (over TCP) Example

   This example code is in the Public Domain (or CC0 licensed, at your option.)

   Unless required by applicable law or agreed to in writing, this
   software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
   CONDITIONS OF ANY KIND, either express or implied.
*/

#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>
#include "esp_wifi.h"
#include "esp_system.h"
#include "nvs_flash.h"
#include "esp_event.h"
#include "esp_netif.h"

#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/semphr.h"
#include "freertos/queue.h"

#include "lwip/sockets.h"
#include "lwip/dns.h"
#include "lwip/netdb.h"

#include "esp_log.h"
#include "mqtt_client.h"
#include "os.h"

#include "user_mqtt.h"

static const char *TAG = "MQTT_EXAMPLE";

/*!!!!!!如下信息请替换成自己在阿里云的信息!!!!!!*/
/*由阿里网平台可得如下信息*/
// ProductKey:"a1tUbQR2faQ"; 
// DeviceName:"dev-esp32"; 
// DeviceSecret:"e624520f169c755e0d02cd0ca99c94c1";
// Region:"cn-shanghai";     

/*下面一参数为自定义*/
// ClientID:="112233";       

/*Broker Address:${YourProductKey}.iot-as-mqtt.${YourRegionId}.aliyuncs.com*/
#define   Aliyun_host       "a1tUbQR2faQ.iot-as-mqtt.cn-shanghai.aliyuncs.com"
#define   Aliyun_port       1883
/*Client ID:     ${ClientID}|securemode=${Mode},signmethod=${SignMethod}|*/
#define   Aliyun_client_id  "112233|securemode=2,signmethod=hmacsha1|"
/*User Name:     ${DeviceName}&${ProductKey}*/
#define   Aliyun_username   "dev-esp32&a1tUbQR2faQ"
/*使用官网 MQTT_Password 工具生成*/
#define   Aliyun_password   "9ABE732ED28BC38EEE7336FA824C26E744413360"

#define   AliyunSubscribeTopic_user_get     "/a1tUbQR2faQ/dev-esp32/user/get"
#define   AliyunPublishTopic_user_update    "/a1tUbQR2faQ/dev-esp32/user/update"

char mqtt_publish_data1[] = "mqtt connect ok ";
char mqtt_publish_data2[] = "mqtt subscribe successful";
char mqtt_publish_data3[] = "mqtt i am esp32";

esp_mqtt_client_handle_t client;

static esp_err_t mqtt_event_handler_cb(esp_mqtt_event_handle_t event)
{
    esp_mqtt_client_handle_t client = event->client;
    int  msg_id;
	
    // your_context_t *context = event->context;
    switch (event->event_id) {
        case MQTT_EVENT_CONNECTED:
            ESP_LOGI(TAG, "MQTT_EVENT_CONNECTED");
            msg_id = esp_mqtt_client_publish(client, AliyunPublishTopic_user_update, mqtt_publish_data1, strlen(mqtt_publish_data1), 1, 0);
            ESP_LOGI(TAG, "sent publish successful, msg_id=%d", msg_id);

            msg_id = esp_mqtt_client_subscribe(client, AliyunSubscribeTopic_user_get, 0);
            ESP_LOGI(TAG, "sent subscribe successful, msg_id=%d", msg_id);

            break;
        case MQTT_EVENT_DISCONNECTED:
            ESP_LOGI(TAG, "MQTT_EVENT_DISCONNECTED");
            break;

        case MQTT_EVENT_SUBSCRIBED:
            ESP_LOGI(TAG, "MQTT_EVENT_SUBSCRIBED, msg_id=%d", event->msg_id);
            msg_id = esp_mqtt_client_publish(client, AliyunPublishTopic_user_update, mqtt_publish_data2, strlen(mqtt_publish_data2), 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);
            break;
        case MQTT_EVENT_PUBLISHED:
            ESP_LOGI(TAG, "MQTT_EVENT_PUBLISHED, msg_id=%d", event->msg_id);
            break;
        case MQTT_EVENT_DATA:
            ESP_LOGI(TAG, "MQTT_EVENT_DATA");
            printf("TOPIC=%.*s\\r\\n", event->topic_len, event->topic);
            printf("DATA=%.*s\\r\\n", event->data_len, event->data);
			
            break;
        case MQTT_EVENT_ERROR:
            ESP_LOGI(TAG, "MQTT_EVENT_ERROR");
            break;
        default:
            ESP_LOGI(TAG, "Other event id:%d", event->event_id);
            break;
    }
    return ESP_OK;
}

static void mqtt_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);
    mqtt_event_handler_cb(event_data);
}

static void mqtt_test_task(void *pvParameters)
{
    uint8_t num = 0;

    while(1)
    {
       esp_mqtt_client_publish(client, AliyunPublishTopic_user_update, mqtt_publish_data3, strlen(mqtt_publish_data3), 1, 0);
       vTaskDelay(2000 / portTICK_PERIOD_MS);
	   if(num++ > 5) break;
	}
    vTaskDelete(NULL);
}


void user_mqtt_app_start(void)
{
    esp_mqtt_client_config_t mqtt_cfg = {
		.host = Aliyun_host,
		.port = Aliyun_port,
		.client_id = Aliyun_client_id,
		.username = Aliyun_username,
		.password = Aliyun_password,

    };

    client = esp_mqtt_client_init(&mqtt_cfg);
    esp_mqtt_client_register_event(client, ESP_EVENT_ANY_ID, mqtt_event_handler, client);
    esp_mqtt_client_start(client);
	
	xTaskCreate(&mqtt_test_task, "mqtt_test_task", 4096, NULL, 5, NULL);
}

4 ESP32工程验证

  1. 编译工程并烧录,串口打印数据如下
    在这里插入图片描述

4.1 ESP32发布消息到阿里云平台

间隔2秒,一共发布6次数据

char mqtt_publish_data3[] = "mqtt i am esp32";

static void mqtt_test_task(void *pvParameters)
{
    uint8_t num = 0;

    while(1)
    {
       esp_mqtt_client_publish(client, AliyunPublishTopic_user_update, mqtt_publish_data3, strlen(mqtt_publish_data3), 1, 0);
       vTaskDelay(2000 / portTICK_PERIOD_MS);
	   if(num++ > 5) break;
	}
    vTaskDelete(NULL);
}

阿里云物联网平台数据如下在这里插入图片描述在这里插入图片描述

4.2 阿里云平台发布消息给ESP32

  1. 在阿里云上发布消息在这里插入图片描述
  2. 查看ESP32串口数据在这里插入图片描述

5 工程链接

gitee仓库平台: ESP32实验

以上是关于ESP32基础应用之使用mqtt连接阿里云物联网平台的主要内容,如果未能解决你的问题,请参考以下文章

ESP32基础应用之使用两个ESP32通过阿里云物联网平台实现相互通信

STM32+ESP8266移植paho MQTT协议连接阿里云物联网平台

阿里云物联网平台配置ESP8266真实设备AT串口连接,支持MQTT协议通信

阿里云物联网平台配置ESP8266真实设备AT串口连接,支持MQTT协议通信

ESP32入门基础之空中升级(OTA)

ESA2GJK1DH1K基础篇: 阿里云物联网平台: 测试MQTT连接阿里云物联网平台