ESP32-C3学习笔记(7)ESP32-C3连接阿里云物联网平台并实现相互通信

1.在阿里云物联网平台建立esp32设备

创建产品与设备ESP32-C3学习笔记(7)ESP32-C3连接阿里云物联网平台并实现相互通信https://help.aliyun.com/document_detail/73705.html?spm=a2c4g.11186623.2.13.541fc5dbZseXQU

2.ESP32-C3新建工程

参考官方例程 examplesprotocolsmqtttcp

3.获取阿里云物联网平台新建的设备参数

ProductKey、DeviceName、DeviceSecret、Region、ClientID

ESP32-C3学习笔记(7)ESP32-C3连接阿里云物联网平台并实现相互通信

得到如下信息

// ProductKey:"gu1apipmzjV"; 
// DeviceName:"dev-esp32c3"; 
// DeviceSecret:"4147b310a3798d203acf81b5855bb38a";
// Region:"cn-shanghai";    
// ClientID:="112233";  //自定义

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

/*Broker Address��${YourProductKey}.iot-as-mqtt.${YourRegionId}.aliyuncs.com*/
#define   Aliyun_host       "gu1apipmzjV.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,timestamp=1644395422811|"
/*User Name��     ${DeviceName}&${ProductKey}*/
#define   Aliyun_username   "dev-esp32c3&gu1apipmzjV"
/*ʹ�ù��� MQTT_Password ��������*/
#define   Aliyun_password   "5920B0AC33810AA9335204A64FA1C171265C7DA0"

 5 ESP32工程主要代码

/* 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 
#include 
#include 
#include 
#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:"gu1apipmzjV"; 
// DeviceName:"dev-esp32c3"; 
// DeviceSecret:"4147b310a3798d203acf81b5855bb38a";
// Region:"cn-shanghai";    


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

/*Broker Address��${YourProductKey}.iot-as-mqtt.${YourRegionId}.aliyuncs.com*/
#define   Aliyun_host       "gu1apipmzjV.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,timestamp=1644395422811|"
/*User Name��     ${DeviceName}&${ProductKey}*/
#define   Aliyun_username   "dev-esp32c3&gu1apipmzjV"
/*ʹ�ù��� MQTT_Password ��������*/
#define   Aliyun_password   "5920B0AC33810AA9335204A64FA1C171265C7DA0"

#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=%.*srn", event->topic_len, event->topic);
            printf("DATA=%.*srn", 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);
}

6.可以在日志中查看上传的数据(UTF-8)

7.点击话题发布可以在esp32-c3串口打印中查看阿里云平台发送过来的数据

本文章来源于互联网,如有侵权,请联系删除!原文地址:ESP32-C3学习笔记(7)ESP32-C3连接阿里云物联网平台并实现相互通信

相关推荐: MQTT工业智能网关支持接入阿里云物模型物联网平台

阿里云物联网平台为设备提供安全可靠的连接通信能力,向下连接海量设备,支撑设备数据采集上云;向上提供云端API,服务端通过调用云端API将指令下发至设备端,实现远程控制。物联网平台也提供了其他增值能力,如设备管理、规则引擎等,为各类IoT场景和行业开发者赋能。厦…