[已解决] 连接MQTT服务器异常
Posted: Thu Jun 17, 2021 3:41 am
- [#include <stdio.h>
- #include <string.h>
- #include <stdlib.h>
- #include "esp_log.h"
- #include "esp_err.h"
- #include "freertos/FreeRTOS.h"
- #include "freertos/task.h"
- #include "freertos/queue.h"
- #include "freertos/event_groups.h"
- #include "driver/gpio.h"
- #include "lwip/err.h"
- #include "lwip/sockets.h"
- #include "lwip/sys.h"
- #include "lwip/dns.h"
- #include "lwip/netdb.h"
- #include "mqtt_client.h"
- #define LOG_TAG "MQTT"
- esp_mqtt_client_handle_t mqtt_client = NULL;
- static void mqtt_event_handler(void* arg, esp_event_base_t event_base,
- int32_t event_id, void* event_data )
- {
- printf("event ID %d\n", event_id );
- switch(event_id )
- {
- case MQTT_EVENT_CONNECTED:
- printf("MQTT_EVENT_CONNECTED\n" );
- esp_mqtt_client_subscribe(mqtt_client, "Test_1", 2 );
- esp_mqtt_client_subscribe(mqtt_client, "Test_2", 1 );
- esp_mqtt_client_subscribe(mqtt_client, "Picture", 2 );
- break;
- case MQTT_EVENT_DISCONNECTED:
- printf("MQTT_EVENT_DISCONNECTED\n" );
- // esp_mqtt_client_reconnect(mqtt_client );
- break;
- case MQTT_EVENT_SUBSCRIBED:
- printf("MQTT_EVENT_SUBSCRIBED\n" );
- // printf("MQTT_EVENT_SUBSCRIBED, msg_id=%d", msg_id);
- break;
- case MQTT_EVENT_UNSUBSCRIBED:
- printf("MQTT_EVENT_DISCONNECTED\n" );
- break;
- case MQTT_EVENT_PUBLISHED:
- printf("MQTT_EVENT_PUBLISHED\n" );
- break;
- case MQTT_EVENT_DATA:
- printf("MQTT_EVENT_DATA\n" );
- // printf("topic length:%d data length:%d\n",event->topic_len,event->data_len);
- // 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:
- printf("MQTT_EVENT_ERROR (%s)\n", (char *)event_data);
- break;
- default:
- printf("Other event id:%d\n", event_id );
- break;
- }
- }
- void esp_mqtt_app_start(void * arg )
- {
- const esp_mqtt_client_config_t mqtt_client_cfg = {
- .host = "127.0.0.1",
- .port= 1883,
- };
- mqtt_client = esp_mqtt_client_init(&mqtt_client_cfg );
- esp_mqtt_client_register_event(mqtt_client, ESP_EVENT_ANY_ID, mqtt_event_handler, NULL);
- /**
- *
- */
- esp_mqtt_client_start(mqtt_client);
- for ( ;; )
- {
- esp_mqtt_client_publish(mqtt_client, "Test_1", "1234567890", 0, 2, 0 );
- vTaskDelay(2000/portTICK_RATE_MS);
- }
- }/Codebox][Codebox=c file=Untitled.c]/* GPIO 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 <string.h>
- #include <stdlib.h>
- #include "freertos/FreeRTOS.h"
- #include "freertos/task.h"
- #include "freertos/queue.h"
- #include "freertos/event_groups.h"
- #include "driver/gpio.h"
- /**
- * 2021-06-03
- */
- #include "driver/spi_master.h"
- #include "driver/rtc_cntl.h"
- #include "soc/rtc.h"
- #include "driver/adc.h"
- #include "nvs_flash.h"
- #include "esp_wifi.h"
- #include "esp_wpa2.h"
- #include "esp_event.h"
- #include "esp_netif.h"
- #include "esp_smartconfig.h"
- #include "esp_partition.h"
- #include "epd_gdeh.h"
- #include "mqtt_client.h"
- /**
- * User modefied by 2021-05-27
- */
- static EventGroupHandle_t s_wifi_event_group = NULL;
- #define SPI_MOSI_IO_NUM 4
- #define SPI_MISO_IO_NUM -1
- #define SPI_SCLK_IO_NUM 16
- extern void gweh_test(void);
- extern void esp_mqtt_app_start(void * arg);
- void usr_spi_tran_cb(spi_transaction_t *trans)
- {
- /**
- * dc = Data / Cmd
- */
- int dc = (int)trans->user;
- gpio_set_level(SPI_DC_IO_NUM, dc );
- return;
- }
- spi_bus_config_t buscfg = {
- .mosi_io_num = SPI_MOSI_IO_NUM,
- .miso_io_num = SPI_MISO_IO_NUM,
- .sclk_io_num = SPI_SCLK_IO_NUM,
- .quadhd_io_num = -1,
- .quadwp_io_num = -1,
- .max_transfer_sz = 100
- };
- rtc_cpu_freq_config_t rtc_freq_cfg = {
- .source = RTC_CPU_FREQ_SRC_8M,
- .source_freq_mhz = 8000000,
- .div = 8,
- .freq_mhz = 1000000
- };
- spi_device_handle_t usr_spi_handler = NULL;
- spi_device_interface_config_t usr_spi_dev_cfg = {
- .flags = SPI_DEVICE_3WIRE|SPI_DEVICE_HALFDUPLEX,
- .command_bits = 0,
- .address_bits = 0,
- .mode = 0,
- .duty_cycle_pos = 0,
- .cs_ena_pretrans= 10,
- .clock_speed_hz = SPI_MASTER_FREQ_8M,
- .input_delay_ns = 0,
- .spics_io_num = SPI_CS_IO_NUM,
- .queue_size = 7,
- .pre_cb = usr_spi_tran_cb
- };
- uint8_t temp_spi_data;
- /* Send a command to the LCD. Uses spi_device_polling_transmit, which waits
- * until the transfer is complete.
- *
- * Since command transactions are usually small, they are handled in polling
- * mode for higher speed. The overhead of interrupt transactions is more than
- * just waiting for the transaction to complete.
- */
- void lcd_cmd(const uint8_t cmd)
- {
- esp_err_t ret;
- spi_transaction_t t;
- memset(&t, 0, sizeof(t)); //Zero out the transaction
- temp_spi_data = cmd;
- t.length=8; //Command is 8 bits
- t.tx_buffer=&temp_spi_data; //The data is the cmd itself
- t.user=(void*)0; //D/C needs to be set to 0
- ret=spi_device_polling_transmit(usr_spi_handler, &t); //Transmit!
- assert(ret==ESP_OK); //Should have had no issues.
- }
- /* Send data to the LCD. Uses spi_device_polling_transmit, which waits until the
- * transfer is complete.
- *
- * Since data transactions are usually small, they are handled in polling
- * mode for higher speed. The overhead of interrupt transactions is more than
- * just waiting for the transaction to complete.
- */
- void lcd_data(const uint8_t data )
- {
- esp_err_t ret;
- spi_transaction_t t;
- temp_spi_data = data;
- memset(&t, 0, sizeof(t)); //Zero out the transaction
- t.length = 8; //Len is in bytes, transaction length is in bits.
- t.tx_buffer = &temp_spi_data; //Data
- t.user=(void*)1; //D/C needs to be set to 1
- ret=spi_device_polling_transmit(usr_spi_handler, &t); //Transmit!
- assert(ret==ESP_OK); //Should have had no issues.
- }
- void ini_spi_test(void * arg )
- {
- for ( ;; )
- {
- printf("Display Picture Start\n");
- gweh_test();
- printf("Display Picture End\n");
- vTaskDelay(60000/portTICK_RATE_MS);
- }
- }
- /* The event group allows multiple bits for each event,
- but we only care about one event - are we connected
- to the AP with an IP? */
- static const int CONNECTED_BIT = BIT0;
- static const int ESPTOUCH_DONE_BIT = BIT1;
- void event_group_task(void * arg )
- {
- static int init_ok = 0;
- EventBits_t cur_event_flag = 0;
- ESP_ERROR_CHECK( esp_smartconfig_set_type(SC_TYPE_ESPTOUCH) );
- smartconfig_start_config_t cfg = SMARTCONFIG_START_CONFIG_DEFAULT();
- ESP_ERROR_CHECK( esp_smartconfig_start(&cfg) );
- for ( ;; )
- {
- cur_event_flag = xEventGroupWaitBits(s_wifi_event_group,
- CONNECTED_BIT | ESPTOUCH_DONE_BIT,
- true, false, portMAX_DELAY );
- if (0x00 != (cur_event_flag&CONNECTED_BIT) )
- {
- printf("the device connected to AP\n");
- }
- else if (0x00 != (cur_event_flag&ESPTOUCH_DONE_BIT) )
- {
- printf("Config Done!");
- if (0x00 == init_ok )
- {
- init_ok = 1;
- xTaskCreate(esp_mqtt_app_start, "esp mqtt app", 2048, NULL, 10, NULL);
- }
- vTaskDelete(NULL );
- }
- }
- }
- static void event_handler(void* arg, esp_event_base_t event_base, int32_t event_id, void *event_data_arg )
- {
- static uint8_t s_cnt = 0;
- s_cnt++;
- if (WIFI_EVENT == event_base )
- {
- printf("------%d------ Wifi (%d) ", s_cnt, event_id);
- if (WIFI_EVENT_STA_START == event_id )
- {
- printf("WIFI_EVENT_STA_START\n" );
- xTaskCreate(event_group_task, "smartconfig_task", 4096, NULL, 3, NULL );
- }
- else if (WIFI_EVENT_STA_STOP == event_id )
- {
- printf("WIFI_EVENT_STA_STOP\n" );
- }
- else if (WIFI_EVENT_STA_CONNECTED == event_id )
- {
- printf("WIFI_EVENT_STA_CONNECTED\n" );
- }
- else if (WIFI_EVENT_SCAN_DONE == event_id )
- {
- printf("WIFI_EVENT_SCAN_DONE\n" );
- }
- else if (WIFI_EVENT_STA_DISCONNECTED == event_id )
- {
- printf("WIFI_EVENT_SCAN_DONE\n" );
- esp_wifi_connect();
- }
- else{
- printf("Unknow WIFI EVENT ID\n" );
- }
- }
- else if (IP_EVENT == event_base )
- {
- printf("------%d------ IP (%d) ", s_cnt, event_id);
- if (IP_EVENT_STA_GOT_IP == event_id )
- {
- /**
- * Device connect suceed.
- */
- printf("Unknow WIFI EVENT ID\n" );
- }
- else{
- printf("Unknow WIFI EVENT ID\n" );
- }
- }
- else if (SC_EVENT == event_base )
- {
- printf("------%d------ SC (%d) ", s_cnt, event_id);
- if (SC_EVENT_SCAN_DONE == event_id )
- {
- printf(" SCAN DONE(%d)\n", event_id );
- }
- else if (SC_EVENT_GOT_SSID_PSWD == event_id )
- {
- printf(" GOT SSID PSWD(%d)\n", event_id );
- smartconfig_event_got_ssid_pswd_t *evt = (smartconfig_event_got_ssid_pswd_t *)event_data_arg;
- wifi_config_t wifi_config;
- uint8_t ssid[33] = { 0 };
- uint8_t password[65] = { 0 };
- bzero(&wifi_config, sizeof(wifi_config_t) );
- memcpy(wifi_config.sta.ssid, evt->ssid, sizeof(wifi_config.sta.ssid) );
- memcpy(wifi_config.sta.password, evt->password, sizeof(wifi_config.sta.password) );
- wifi_config.sta.bssid_set = evt->bssid_set;
- if (true == wifi_config.sta.bssid_set ){
- memcpy(wifi_config.sta.bssid, evt->bssid, sizeof(wifi_config.sta.bssid) );
- }
- printf("Wifi ssid (%s)\n", wifi_config.sta.ssid);
- printf("Wifi password (%s)\n", wifi_config.sta.password);
- printf("Wifi bssid (%s)\n", wifi_config.sta.bssid);
- ESP_ERROR_CHECK(esp_wifi_disconnect() );
- ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_config ) );
- esp_wifi_connect();
- xEventGroupSetBits(s_wifi_event_group, CONNECTED_BIT );
- }
- else if (SC_EVENT_FOUND_CHANNEL == event_id )
- {
- printf(" FOUND CHANNEL(%d)\n", event_id );
- }
- else if (SC_EVENT_SEND_ACK_DONE == event_id )
- {
- printf(" ACK from DEVICE to ESPTOUCH (%d)\n", event_id );
- xEventGroupSetBits(s_wifi_event_group, ESPTOUCH_DONE_BIT );
- }
- else{
- printf(" Unknow SC Message (%d)\n", event_id );
- }
- }
- else{
- printf("Unknow EVENT BASE\n" );
- }
- }
- static void init_wifi(void )
- {
- ESP_ERROR_CHECK(nvs_flash_init() );
- //static esp_partition_t * s_user_partiton = NULL;
- // uint8_t * usr_test_buf = calloc(0x100, sizeof(uint8_t));
- // if (NULL == usr_test_buf )
- // {
- // printf("Not have enough space\n");
- // return;
- // }
- // int ret = 0x00;
- // memset(usr_test_buf, 0x00, 0x100);
- // /**
- // * 打印flash 中数据。对flash中数据进行读写操作。
- // */
- // s_user_partiton = esp_partition_find_first(ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_DATA_PHY, "usr_data" );
- // if (NULL == s_user_partiton )
- // {
- // printf("find (usr_data) Err \n");
- // }
- // else{
- // printf("Partiton esp_partition_type_t: %d\n", s_user_partiton->type );
- // printf("Partiton esp_partition_subtype_t: %d\n", s_user_partiton->subtype );
- // printf("Partiton label: %s\n", s_user_partiton->label );
- // printf("Partiton address: 0x%08x\n", s_user_partiton->address );
- // printf("Partiton size: %d\n", s_user_partiton->size );
- // }
- // /**
- // * Read Partition.
- // */
- // ret = esp_partition_read(s_user_partiton, 0x00, usr_test_buf, 0x100 );
- // if (ESP_OK != ret )
- // { printf("Read partiton Err %d", ret ); }
- // printf("Read data:\n");
- // for (int i = 0; i < 0x100; i++ )
- // {
- // printf("0x%02x ", usr_test_buf[i] );
- // if (63 == i%64 )
- // {
- // printf("\n");
- // }
- // }
- // printf("Read data end\n");
- // /**
- // * Write Partition.
- // */
- // memset(usr_test_buf, 0xaa, 0x100);
- // ret = esp_partition_erase_range(s_user_partiton, 0x00, 0x1000);
- // if (ESP_OK != ret )
- // { printf("Erase partiton Err %d\n", ret ); }
- // else
- // { printf("Erase partiton OK\n");}
- // ret = esp_partition_write(s_user_partiton, 0x00, usr_test_buf, 0x100 );
- // if (ESP_OK != ret )
- // { printf("Write partiton Err %d\n", ret ); }
- // memset(usr_test_buf, 0x00, 0x100 );
- // /**
- // * Read Partition Again.
- // */
- // ret = esp_partition_read(s_user_partiton, 0x00, usr_test_buf, 0x100 );
- // if (ESP_OK != ret )
- // { printf("Read partiton Err %d", ret ); }
- // printf("Read data Again:\n");
- // for (int i = 0; i < 0x100; i++ )
- // {
- // printf("0x%02x ", usr_test_buf[i] );
- // if (63 == i%64 )
- // {
- // printf("\n");
- // }
- // }
- // printf("Read data again end\n");
- // ret = esp_partition_erase_range(s_user_partiton, 0x00, 0x1000);
- // if (ESP_OK != ret )
- // { printf("Erase partiton Err %d\n", ret ); }
- // else
- // { printf("Erase partiton OK\n");}
- // memset(usr_test_buf, 0x55, 0x100);
- // ret = esp_partition_write(s_user_partiton, 0x00, usr_test_buf, 0x100 );
- // if (ESP_OK != ret )
- // { printf("Write partiton Err %d", ret ); }
- // free(usr_test_buf);
- ESP_ERROR_CHECK(esp_netif_init() );
- s_wifi_event_group = xEventGroupCreate();
- ESP_ERROR_CHECK(esp_event_loop_create_default() );
- esp_netif_t * sta_netif = esp_netif_create_default_wifi_sta();
- /**
- * assert 用于判断指针是否为0. 若不为0,打印相关信息。
- */
- assert(sta_netif );
- /**
- * wifi 初始化.
- */
- wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
- ESP_ERROR_CHECK(esp_wifi_init(&cfg ) );
- /**
- * 注册事件处理方法.
- */
- ESP_ERROR_CHECK(esp_event_handler_register(WIFI_EVENT, ESP_EVENT_ANY_ID, event_handler, NULL) );
- ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP, event_handler, NULL) );
- ESP_ERROR_CHECK(esp_event_handler_register(SC_EVENT, ESP_EVENT_ANY_ID, event_handler, NULL) );
- /**
- * 设置wifi模式,启动wifi
- */
- ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA) );
- ESP_ERROR_CHECK(esp_wifi_start() );
- }
- /**
- * Brief:
- * This test code shows how to configure gpio and how to use gpio interrupt.
- *
- * GPIO status:
- * GPIO18: output
- * GPIO19: output
- * GPIO4: input, pulled up, interrupt from rising edge and falling edge
- * GPIO5: input, pulled up, interrupt from rising edge.
- *
- * Test:
- * Connect GPIO18 with GPIO4
- * Connect GPIO19 with GPIO5
- * Generate pulses on GPIO18/19, that triggers interrupt on GPIO4/5
- *
- */
- #define GPIO_OUTPUT_IO_0 25
- #define GPIO_OUTPUT_IO_1 26
- #define GPIO_OUTPUT_PIN_SEL ((1ULL<<GPIO_OUTPUT_IO_0) | (1ULL<<GPIO_OUTPUT_IO_1))
- #define GPIO_INPUT_IO_0 2
- #define GPIO_INPUT_IO_1 15
- #define GPIO_INPUT_PIN_SEL ((1ULL<<GPIO_INPUT_IO_0) | (1ULL<<GPIO_INPUT_IO_1))
- #define ESP_INTR_FLAG_DEFAULT 0
- static xQueueHandle gpio_evt_queue = NULL;
- static void IRAM_ATTR gpio_isr_handler(void* arg)
- {
- uint32_t gpio_num = (uint32_t) arg;
- xQueueSendFromISR(gpio_evt_queue, &gpio_num, NULL);
- }
- static void gpio_task_example(void* arg)
- {
- uint32_t io_num;
- for(;;) {
- if(xQueueReceive(gpio_evt_queue, &io_num, portMAX_DELAY)) {
- printf("GPIO[%d] intr, val: %d\n", io_num, gpio_get_level(io_num));
- }
- }
- }
- void app_main(void)
- {
- gpio_config_t io_conf;
- //disable interrupt
- io_conf.intr_type = GPIO_PIN_INTR_DISABLE;
- //set as output mode
- io_conf.mode = GPIO_MODE_OUTPUT;
- //bit mask of the pins that you want to set,e.g.GPIO18/19
- io_conf.pin_bit_mask = GPIO_OUTPUT_PIN_SEL;
- //disable pull-down mode
- io_conf.pull_down_en = 0;
- //disable pull-up mode
- io_conf.pull_up_en = 0;
- //configure GPIO with the given settings
- gpio_config(&io_conf);
- //interrupt of rising edge
- io_conf.intr_type = GPIO_PIN_INTR_POSEDGE;
- //bit mask of the pins, use GPIO4/5 here
- io_conf.pin_bit_mask = GPIO_INPUT_PIN_SEL;
- //set as input mode
- io_conf.mode = GPIO_MODE_INPUT;
- //enable pull-up mode
- io_conf.pull_up_en = 1;
- gpio_config(&io_conf);
- //change gpio intrrupt type for one pin
- gpio_set_intr_type(GPIO_INPUT_IO_0, GPIO_INTR_ANYEDGE);
- gpio_set_direction(SPI_DC_IO_NUM, GPIO_MODE_OUTPUT );
- gpio_set_direction(SPI_RST_IO_NUM, GPIO_MODE_OUTPUT );
- gpio_set_direction(SPI_BUSY_IO_NUM, GPIO_MODE_INPUT );
- spi_bus_initialize(SPI2_HOST, &buscfg, 0 );
- ESP_ERROR_CHECK(spi_bus_add_device(SPI2_HOST, &usr_spi_dev_cfg, &usr_spi_handler) );
- //create a queue to handle gpio event from isr
- gpio_evt_queue = xQueueCreate(10, sizeof(uint32_t));
- //start gpio task
- xTaskCreate(gpio_task_example, "gpio_task_example", 2048, NULL, 10, NULL);
- //install gpio isr service
- gpio_install_isr_service(ESP_INTR_FLAG_DEFAULT);
- //hook isr handler for specific gpio pin
- gpio_isr_handler_add(GPIO_INPUT_IO_0, gpio_isr_handler, (void*) GPIO_INPUT_IO_0);
- //hook isr handler for specific gpio pin
- gpio_isr_handler_add(GPIO_INPUT_IO_1, gpio_isr_handler, (void*) GPIO_INPUT_IO_1);
- //remove isr handler for gpio number.
- gpio_isr_handler_remove(GPIO_INPUT_IO_0);
- //hook isr handler for specific gpio pin again
- gpio_isr_handler_add(GPIO_INPUT_IO_0, gpio_isr_handler, (void*) GPIO_INPUT_IO_0);
- init_wifi();
- xTaskCreate(ini_spi_test, "ini spi test\n", 4096, NULL, 3, NULL );
- int cnt = 0;
- while(1) {
- printf("cnt: %d\n", cnt++);
- vTaskDelay(1000 / portTICK_RATE_MS);
- gpio_set_level(GPIO_OUTPUT_IO_0, cnt % 2);
- gpio_set_level(GPIO_OUTPUT_IO_1, cnt % 2);
- }
- }
- E (861562) TRANS_TCP: [sock=54] delayed connect error: Connection reset by peer
- E (861562) MQTT_CLIENT: Error transport connect