ESP32 阿里云 入门学习②

EPS32连接阿里云-入门学习QQ群1067739808

  • 如何修改MQTT工程并实现远程连接阿里云

辛苦编写未经允许禁止转发
大家好本人第一次使用CSDN写技术文档,如有不足之处多多指教,开门见山,本人在ESP系列开发中是零基础以前也没有用过相关IDE和编译环境,编译工程都是在大神群里软磨硬泡,学习ESP32真的是全是眼泪,本人技术有限所以尽我所能尽量详细的讲一下我怎么调通的ESP32并且连接上了阿里云。

如何修改MQTT工程并实现远程连接阿里云

  1. 首先使用eclipse打开ESP-IDF工程中的MQTT工程他在那里呢?C:\Ai-ThinkerIDE-V1.0\AiThinkerIDE_V1.0\msys32\home\aithinker\esp-idf\examples\protocols\mqtt\tcp,那么我们要修改要编译的工程路径如图所示(不知道怎么修改的请看第一篇文章):
    ESP32 阿里云 入门学习②_第1张图片
  2. 你想用ESP32连接阿里云第一个条件肯定是有wifi联网,没有网络什么的干不了,第一次接触ESP32工程我找了半天,在哪里能设置WiFi信息啊,完全没头绪,你看了我这个文档一下子就豁然开朗了记不记得前文配置了一个menuconfig,在这里他就有用了,他可以配置项目的WiFi连接信息,我们点击工程右键Make Targets->Build选择menuconfig,会跳出来一个配置界面,选择Example connection configuration在里面设置SSID和Password,如下图所示设置好点击SAVE保存:
    ESP32 阿里云 入门学习②_第2张图片
    ESP32 阿里云 入门学习②_第3张图片
  3. 配置下载程序后设备上电就会连接设定的Wifi(中文名称会连接失败),下面开始修改代码,代码在右侧工程树中examples->protocols->mqtt->tcp->main->app_main.c这里就是代码了,首先我们要配置下mqtt代码如下所示:
esp_mqtt_client_config_t mqtt_cfg = {
    	.host = "a1UF4taFJc3.iot-as-mqtt.cn-shanghai.aliyuncs.com",
		.port = 1883,
		.client_id = "liujiaolong|securemode=3\,signmethod=hmacsha1|",
		.username = "mcuiot&a1UF4taFJc3",
		.password = "29CF6A505005B36F529E4F505DFAF1270AA6EE07",
    };

上面的代码是核心了,如果知道怎么来的请看第一章的阿里云相关内容,这个配置好就能保证设备可以连接阿里云了,下面我们在修改一些订阅与推送的Topic路径就可以在阿里云和串口中看先相关的数据信息,app_main.c全部代码如下(读者感觉情况修改自己的Topic路径),代码中我加了对GPIO的控制为之后上位机通过阿里云控制打下基础:

/* 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 "tcpip_adapter.h"
#include "protocol_examples_common.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 "driver/gpio.h"

static const char *TAG = "MQTT_EXAMPLE";

#define GPIO_OUTPUT_IO_0    22
#define GPIO_OUTPUT_IO_1    19

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;

    char Mqtt_data[100];

    // your_context_t *context = event->context;
    switch (event->event_id) {
        //MQTT事件已连接
        case MQTT_EVENT_CONNECTED:
            ESP_LOGI(TAG, "MQTT_EVENT_CONNECTED");
            //推送一个消息
            msg_id = esp_mqtt_client_publish(client, "/a1UF4taFJc3/mcuiot/user/tongxin", "{\"Status\":1\,\"Data\":\"Hello\, World!\"}", 0, 1, 0);
            ESP_LOGI(TAG, "sent publish successful, msg_id=%d", msg_id);
            //订阅
            msg_id = esp_mqtt_client_subscribe(client, "/a1UF4taFJc3/mcuiot/user/tongxin", 0);
            ESP_LOGI(TAG, "sent subscribe successful, msg_id=%d", msg_id);

            break;
        //MQTT事件断开
        case MQTT_EVENT_DISCONNECTED:
            ESP_LOGI(TAG, "MQTT_EVENT_DISCONNECTED");
            break;
        //MQTT事件订阅
        case MQTT_EVENT_SUBSCRIBED:
            ESP_LOGI(TAG, "MQTT_EVENT_SUBSCRIBED, msg_id=%d", event->msg_id);
            //推送一个消息
            msg_id = esp_mqtt_client_publish(client, "/a1UF4taFJc3/mcuiot/user/tongxin", "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);
            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);
            sprintf(Mqtt_data,"%.*s", event->data_len , event->data);
			printf("Mqtt_data=%s\r\n", Mqtt_data);
            //根据内容控制GPIO
            if (strcmp(Mqtt_data, "{\"Status\":1,\"Data\":0}") == 0) {
            	gpio_set_level(GPIO_OUTPUT_IO_0, 0);
            }else if (strcmp(Mqtt_data, "{\"Status\":1,\"Data\":1}") == 0) {
            	gpio_set_level(GPIO_OUTPUT_IO_0, 1);
            }else if (strcmp(Mqtt_data, "{\"Status\":2,\"Data\":0}") == 0) {
            	gpio_set_level(GPIO_OUTPUT_IO_1, 0);
            }else if (strcmp(Mqtt_data, "{\"Status\":2,\"Data\":1}") == 0) {
            	gpio_set_level(GPIO_OUTPUT_IO_1, 1);
            }else{
            	gpio_set_level(GPIO_OUTPUT_IO_0, 1);
            	gpio_set_level(GPIO_OUTPUT_IO_1, 1);
            }

            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_app_start(void)
{
    esp_mqtt_client_config_t mqtt_cfg = {
    	.host = "a1UF4taFJc3.iot-as-mqtt.cn-shanghai.aliyuncs.com",
		.port = 1883,
		.client_id = "liujiaolong|securemode=3\,signmethod=hmacsha1|",
		.username = "mcuiot&a1UF4taFJc3",
		.password = "29CF6A505005B36F529E4F505DFAF1270AA6EE07",
    };
#if CONFIG_BROKER_URL_FROM_STDIN
    char line[128];

    if (strcmp(mqtt_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);
        }
        mqtt_cfg.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(&mqtt_cfg);
    esp_mqtt_client_register_event(client, ESP_EVENT_ANY_ID, mqtt_event_handler, client);
    esp_mqtt_client_start(client);
}

void app_main(void)
{
	//配置GPIO
    gpio_pad_select_gpio(GPIO_OUTPUT_IO_0);
    /* Set the GPIO as a push/pull output */
    gpio_set_direction(GPIO_OUTPUT_IO_0, GPIO_MODE_OUTPUT);

    gpio_pad_select_gpio(GPIO_OUTPUT_IO_1);
	/* Set the GPIO as a push/pull output */
	gpio_set_direction(GPIO_OUTPUT_IO_1, GPIO_MODE_OUTPUT);


    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_TCP", ESP_LOG_VERBOSE);
    esp_log_level_set("TRANSPORT_SSL", 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());
    tcpip_adapter_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());

    mqtt_app_start();
}

  1. 上面的代码需要自己理解下我有些简单的备注,下面开始烧写工程,Make Target中点击下载,开始漫长的等待,成功后会有这种提示信息,阿里云会显示在线,打开串口会看见如下信息,如图所示:
    ESP32 阿里云 入门学习②_第4张图片
    打开串口查看数据,wifi连接成功如图所示:
    ESP32 阿里云 入门学习②_第5张图片
    连接阿里云MQTT服务并发送信息如图所示:
    ESP32 阿里云 入门学习②_第6张图片
  2. 测试连接是否成功,首先打开阿里云物联网,找到设备看是否在线如图所示(在线设备连接成功):
    ESP32 阿里云 入门学习②_第7张图片
  3. 阿里云在自定义topic中发送数据给ESP32验证通信成功,因为程序中订阅了我们之前定义的topic类,所以可以收到这个推送,操作结果如图所示:
    ESP32 阿里云 入门学习②_第8张图片
    串口中会收到这条推送信息如图所示:
    ESP32 阿里云 入门学习②_第9张图片
    至此ESP32设备连接阿里云就算成功了。有些知识点要细品细研究,写的不详细的欢迎加群讨论。
    硬件实物图如下所示:

你可能感兴趣的:(ESP32连接阿里云,ESP32入门使用)