esp8266rtos3.0  wifi及mqtt

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_36063855/article/details/90485229

/*
   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 <stdlib.h>
#include <string.h>

#include "esp_system.h"
#include "esp_wifi.h"
#include "driver/uart.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"
#include "esp_event.h"
#include "esp_event_loop.h"
#include "mqtt_client.h"
#include "nvs_flash.h"

#define MQTT_HOST                  // MQTT服务端域名/IP地址    
#define MQTT_PORT           1883                                            // 网络连接端口号        
#define MQTT_CLIENT_ID         // 官方例程中是"Device_ID"        // 客户端标识符        
#define MQTT_USER                         // MQTT用户名                
#define MQTT_PASS              // MQTT密码                    

#define STA_SSID                     // WIFI名称                
#define STA_PASS                // WIFI密码                

TaskHandle_t wifi_Handle = NULL;
void wifi_Task(void *pvParameters);
static EventGroupHandle_t wifi_event_group;

const int WIFI_CONNECTED_BIT = BIT0;
static const char *TAG = "simple wifi";
static void mqtt_app_init(void);
char buf[4096];

static void delay_ms(uint16_t nms)
{
   vTaskDelay(nms / portTICK_PERIOD_MS);
}

static esp_err_t mqtt_event_handler(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, "/topic/qos1", "data_3", 0, 1, 0);
            msg_id = esp_mqtt_client_publish(client, "/sys/a1VCMJsiusS/1234/thing/service/property/set", buf, 4041, 1, 0);
            ESP_LOGI(TAG, "sent publish successful, msg_id=%d", msg_id);

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

 //           msg_id = esp_mqtt_client_subscribe(client, "/topic/qos1", 1);
 //           ESP_LOGI(TAG, "sent subscribe successful, msg_id=%d", msg_id);

 //           msg_id = esp_mqtt_client_unsubscribe(client, "/topic/qos1");
 //           ESP_LOGI(TAG, "sent unsubscribe 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, "/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);
            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;
    }
    return ESP_OK;
}


static esp_err_t event_handler(void *ctx, system_event_t *event)
{
    switch(event->event_id) {
    //ESP8266 station start 
    case SYSTEM_EVENT_STA_START:
        esp_wifi_connect();
        break;
    //ESP8266 station got IP from connected AP 获取IP
    case SYSTEM_EVENT_STA_GOT_IP:
        ESP_LOGI(TAG, "got ip:%s",
                ip4addr_ntoa(&event->event_info.got_ip.ip_info.ip));
        xEventGroupSetBits(wifi_event_group, WIFI_CONNECTED_BIT);
        if(wifi_Handle == NULL)
        {
            xTaskCreate((TaskFunction_t) wifi_Task,
                    (const char *)"wifi_Task",
                    (uint16_t)2048,
                    (void *)event,
                    (UBaseType_t)1,
                    (TaskHandle_t *)wifi_Handle);
        }

        break;
        //a station connected to ESP8266 soft-AP  连接到AP
    case SYSTEM_EVENT_AP_STACONNECTED:
        ESP_LOGI(TAG, "station:"MACSTR" join, AID=%d",
                MAC2STR(event->event_info.sta_connected.mac),
                 event->event_info.sta_connected.aid);
        break;
    //a station disconnected from ESP8266 soft-AP   未连接上AP
    case SYSTEM_EVENT_AP_STADISCONNECTED:
        ESP_LOGI(TAG, "station:"MACSTR"leave, AID=%d",
                 MAC2STR(event->event_info.sta_disconnected.mac),
                 event->event_info.sta_disconnected.aid);
        break;
    //ESP8266 station disconnected from AP      断开
    case SYSTEM_EVENT_STA_DISCONNECTED:
        if(NULL != wifi_Handle)
        {
            vTaskDelete(wifi_Handle);
            wifi_Handle = NULL;
        }
        esp_wifi_connect();
        xEventGroupClearBits(wifi_event_group, WIFI_CONNECTED_BIT);
        break;
    default:
        break;
    }
    return ESP_OK;
}

/******************************************************************************
 * FunctionName : app_main
 * Description  : entry of user application, init user function here
 * Parameters   : none
 * Returns      : none
 *******************************************************************************/
void app_main(void)
{
    uint16_t i = 0;
    //设置串口波特率
    uart_set_baudrate(UART_NUM_0, 115200);
    delay_ms(1000);
    //打印SDK版本
    printf("SDK version:%s\n", esp_get_idf_version());
    for(i = 0; i < 4096; i++)
    {
        buf[i] = i % 10 + '0';
    }

    nvs_flash_init();

    //创建事件组
    wifi_event_group = xEventGroupCreate();
    //初始化TCPIP适配器。
    tcpip_adapter_init();
    //注册事件处理函数初始化
    ESP_ERROR_CHECK( esp_event_loop_init(event_handler, NULL) );
    //获取wifi初始化参数
    wifi_init_config_t wifi_init_cf = WIFI_INIT_CONFIG_DEFAULT();
    wifi_config_t wifi_cf = {
        .sta = {
            .ssid = STA_SSID,
            .password = STA_PASS 
        }
    };
    //初始化wifi 
    ESP_ERROR_CHECK(esp_wifi_init(&wifi_init_cf));
    //设置模式
    ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
    //设置WIFI账号密码
    ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_cf));
    //启动wifi
    ESP_ERROR_CHECK(esp_wifi_start());


    
    mqtt_app_init();

}

static void mqtt_app_init(void)
{
    esp_mqtt_client_config_t mqtt_cfg = {
        //事件
        .event_handle = mqtt_event_handler,
        //.host = "139.196.135.135",
        .host = MQTT_HOST,
        .port = MQTT_PORT, 
        .client_id = MQTT_CLIENT_ID,
        .username = MQTT_USER,
        .password = MQTT_PASS,
        .buffer_size = 4096
    };

    esp_mqtt_client_handle_t client = esp_mqtt_client_init(&mqtt_cfg);
    esp_mqtt_client_start(client);
}

void wifi_Task(void *pvParameters)
{
    system_event_t *event = pvParameters;
    while(1)
    {
//        printf("ip = %s\r\n", ip4addr_ntoa(&event->event_info.got_ip.ip_info.ip));
        delay_ms(500);    
    }
}

展开阅读全文

没有更多推荐了,返回首页