2

One ESP32 is in APSTA mode

  • AP to other ESP32
  • STA to keep it connecting it to the internet

This worked fine after testing it

The mosquitto config file is as follows:-

listener 1883 
allow_anonymous true

And on the other, I am trying to use the example from esp-idf protocol/MQTT/tcp

In idf.py menuconfig :-

  • I changed the username and password (ESP32 connection to AP is not an issue reason being I tested the wifi/getting_started/station and it worked fine)
  • Default broker URL mqtt://mqtt.eclipseprojects.io

then after erasing flash using esptool.py --port /dev/ttyUSB0 erase_flash

After build I uploaded the code to ESP32 using

idf.py build
idf.py -p /dev/ttyUSB0 flash

And when I monitor it

idf.py -p /dev/ttyUSB0 monitor

It showed the following error

E (562605) esp-tls: couldn't get hostname for :mqtt.eclipseprojects.io: getaddrinfo() returns 202, addrinfo=0x0
E (562605) transport_base: Failed to open a new connection: 32769
E (562605) mqtt_client: Error transport connect
I (562615) MQTT_EXAMPLE: MQTT_EVENT_ERROR
E (562615) MQTT_EXAMPLE: Last error reported from esp-tls: 0x8001
I (562625) MQTT_EXAMPLE: Last errno string (Success)
I (562625) MQTT_EXAMPLE: MQTT_EVENT_DISCONNECTED
I (572635) MQTT_EXAMPLE: Other event id:7

Here is the protocol/MQTT/tcp code that I mentioned in question and APSTA-code as mentioned in question

APSTA main code file


/* The example of ESP-IDF
 *
 * This sample code is in the public domain.
 */

#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"
#include "esp_system.h"
#include "esp_wifi.h"
#include "esp_event.h"
#include "esp_log.h"
#include "nvs_flash.h"

static const char *TAG = "MAIN";

static EventGroupHandle_t wifi_event_group;
const int CONNECTED_BIT = BIT0;


static void event_handler(void* arg, esp_event_base_t event_base,
                                int32_t event_id, void* event_data)
{
    if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) {
        ESP_LOGI(TAG, "WIFI_EVENT_STA_DISCONNECTED");
        esp_wifi_connect();
        xEventGroupClearBits(wifi_event_group, CONNECTED_BIT);
    } else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) {
        ESP_LOGI(TAG, "IP_EVENT_STA_GOT_IP");
        xEventGroupSetBits(wifi_event_group, CONNECTED_BIT);
    }
}

static void initialise_wifi(void)
{
    esp_log_level_set("wifi", ESP_LOG_WARN);
    static bool initialized = false;
    if (initialized) {
        return;
    }
    ESP_ERROR_CHECK(esp_netif_init());
    wifi_event_group = xEventGroupCreate();
    ESP_ERROR_CHECK(esp_event_loop_create_default());
    esp_netif_t *ap_netif = esp_netif_create_default_wifi_ap();
    assert(ap_netif);
    esp_netif_t *sta_netif = esp_netif_create_default_wifi_sta();
    assert(sta_netif);
    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, WIFI_EVENT_STA_DISCONNECTED, &event_handler, NULL) );
    ESP_ERROR_CHECK( esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &event_handler, NULL) );

    ESP_ERROR_CHECK( esp_wifi_set_storage(WIFI_STORAGE_RAM) );
    ESP_ERROR_CHECK( esp_wifi_set_mode(WIFI_MODE_NULL) );
    ESP_ERROR_CHECK( esp_wifi_start() );

    initialized = true;
}

#if CONFIG_WIFI_CONNECT_AP
static bool wifi_ap(void)
{
    wifi_config_t wifi_config = { 0 };
    strcpy((char *)wifi_config.ap.ssid,CONFIG_AP_WIFI_SSID);
    strcpy((char *)wifi_config.ap.password, CONFIG_AP_WIFI_PASSWORD);
    wifi_config.ap.authmode = WIFI_AUTH_WPA_WPA2_PSK;
    wifi_config.ap.ssid_len = strlen(CONFIG_AP_WIFI_SSID);
    wifi_config.ap.max_connection = CONFIG_AP_MAX_STA_CONN;
    wifi_config.ap.channel = CONFIG_AP_WIFI_CHANNEL;

    if (strlen(CONFIG_AP_WIFI_PASSWORD) == 0) {
        wifi_config.ap.authmode = WIFI_AUTH_OPEN;
    }


    ESP_ERROR_CHECK( esp_wifi_set_mode(WIFI_MODE_AP) );
    ESP_ERROR_CHECK( esp_wifi_set_config(ESP_IF_WIFI_AP, &wifi_config) );
    ESP_ERROR_CHECK( esp_wifi_start() );
    ESP_LOGI(TAG, "WIFI_MODE_AP started. SSID:%s password:%s channel:%d",
             CONFIG_AP_WIFI_SSID, CONFIG_AP_WIFI_PASSWORD, CONFIG_AP_WIFI_CHANNEL);
    return ESP_OK;
}
#endif


#if CONFIG_WIFI_CONNECT_STA
static bool wifi_sta(int timeout_ms)
{
    wifi_config_t wifi_config = { 0 };
    strcpy((char *)wifi_config.sta.ssid, CONFIG_STA_WIFI_SSID);
    strcpy((char *)wifi_config.sta.password, CONFIG_STA_WIFI_PASSWORD);

    ESP_ERROR_CHECK( esp_wifi_set_mode(WIFI_MODE_STA) );
    ESP_ERROR_CHECK( esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_config) );
    ESP_ERROR_CHECK( esp_wifi_connect() );

    int bits = xEventGroupWaitBits(wifi_event_group, CONNECTED_BIT,
                                   pdFALSE, pdTRUE, timeout_ms / portTICK_PERIOD_MS);
    ESP_LOGI(TAG, "bits=%x", bits);
    if (bits) {
        ESP_LOGI(TAG, "WIFI_MODE_STA connected. SSID:%s password:%s",
             CONFIG_STA_WIFI_SSID, CONFIG_STA_WIFI_PASSWORD);
    } else {
        ESP_LOGI(TAG, "WIFI_MODE_STA can't connected. SSID:%s password:%s",
             CONFIG_STA_WIFI_SSID, CONFIG_STA_WIFI_PASSWORD);
    }
    return (bits & CONNECTED_BIT) != 0;
}
#endif

#if CONFIG_WIFI_CONNECT_APSTA
static bool wifi_apsta(int timeout_ms)
{
    wifi_config_t ap_config = { 0 };
    strcpy((char *)ap_config.ap.ssid,CONFIG_AP_WIFI_SSID);
    strcpy((char *)ap_config.ap.password, CONFIG_AP_WIFI_PASSWORD);
    ap_config.ap.authmode = WIFI_AUTH_WPA_WPA2_PSK;
    ap_config.ap.ssid_len = strlen(CONFIG_AP_WIFI_SSID);
    ap_config.ap.max_connection = CONFIG_AP_MAX_STA_CONN;
    ap_config.ap.channel = CONFIG_AP_WIFI_CHANNEL;

    if (strlen(CONFIG_AP_WIFI_PASSWORD) == 0) {
        ap_config.ap.authmode = WIFI_AUTH_OPEN;
    }

    wifi_config_t sta_config = { 0 };
    strcpy((char *)sta_config.sta.ssid, CONFIG_STA_WIFI_SSID);
    strcpy((char *)sta_config.sta.password, CONFIG_STA_WIFI_PASSWORD);


    ESP_ERROR_CHECK( esp_wifi_set_mode(WIFI_MODE_APSTA) );
    ESP_ERROR_CHECK( esp_wifi_set_config(ESP_IF_WIFI_AP, &ap_config) );
    ESP_ERROR_CHECK( esp_wifi_set_config(ESP_IF_WIFI_STA, &sta_config) );
    ESP_ERROR_CHECK( esp_wifi_start() );
    ESP_LOGI(TAG, "WIFI_MODE_AP started. SSID:%s password:%s channel:%d",
             CONFIG_AP_WIFI_SSID, CONFIG_AP_WIFI_PASSWORD, CONFIG_AP_WIFI_CHANNEL);

    ESP_ERROR_CHECK( esp_wifi_connect() );
    int bits = xEventGroupWaitBits(wifi_event_group, CONNECTED_BIT,
                                   pdFALSE, pdTRUE, timeout_ms / portTICK_PERIOD_MS);
    ESP_LOGI(TAG, "bits=%x", bits);
    if (bits) {
        ESP_LOGI(TAG, "WIFI_MODE_STA connected. SSID:%s password:%s",
             CONFIG_STA_WIFI_SSID, CONFIG_STA_WIFI_PASSWORD);
    } else {
        ESP_LOGI(TAG, "WIFI_MODE_STA can't connected. SSID:%s password:%s",
             CONFIG_STA_WIFI_SSID, CONFIG_STA_WIFI_PASSWORD);
    }
    return (bits & CONNECTED_BIT) != 0;
}
#endif

void app_main()
{
    esp_err_t err = nvs_flash_init();
    if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND) {
        ESP_ERROR_CHECK( nvs_flash_erase() );
        err = nvs_flash_init();
    }
    ESP_ERROR_CHECK(err);

    initialise_wifi();

#if CONFIG_WIFI_CONNECT_AP
    ESP_LOGW(TAG, "Start AP Mode");
    wifi_ap();
#elif CONFIG_WIFI_CONNECT_STA
    ESP_LOGW(TAG, "Start STA Mode");
    wifi_sta(CONFIG_STA_CONNECT_TIMEOUT*1000);
#elif CONFIG_WIFI_CONNECT_APSTA
    ESP_LOGW(TAG, "Start APSTA Mode");
    wifi_apsta(CONFIG_STA_CONNECT_TIMEOUT*1000);
#endif
}

protocal/mqtt/tcp code


/* 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 "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"

static const char *TAG = "MQTT_EXAMPLE";


static void log_error_if_nonzero(const char *message, int error_code)
{
    if (error_code != 0) {
        ESP_LOGE(TAG, "Last error %s: 0x%x", message, error_code);
    }
}

/*
 * @brief Event handler registered to receive MQTT events
 *
 *  This function is called by the MQTT client event loop.
 *
 * @param handler_args user data registered to the event.
 * @param base Event base for the handler(always MQTT Base in this example).
 * @param event_id The id for the received event.
 * @param event_data The data for the event, esp_mqtt_event_handle_t.
 */
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);
    esp_mqtt_event_handle_t event = event_data;
    esp_mqtt_client_handle_t client = event->client;
    int msg_id;
    switch ((esp_mqtt_event_id_t)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);
        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");
        if (event->error_handle->error_type == MQTT_ERROR_TYPE_TCP_TRANSPORT) {
            log_error_if_nonzero("reported from esp-tls", event->error_handle->esp_tls_last_esp_err);
            log_error_if_nonzero("reported from tls stack", event->error_handle->esp_tls_stack_err);
            log_error_if_nonzero("captured as transport's socket errno",  event->error_handle->esp_transport_sock_errno);
            ESP_LOGI(TAG, "Last errno string (%s)", strerror(event->error_handle->esp_transport_sock_errno));

        }
        break;
    default:
        ESP_LOGI(TAG, "Other event id:%d", event->event_id);
        break;
    }
}

static void mqtt_app_start(void)
{
    esp_mqtt_client_config_t mqtt_cfg = {
        .broker.address.uri = CONFIG_BROKER_URL,
    };
#if CONFIG_BROKER_URL_FROM_STDIN
    char line[128];

    if (strcmp(mqtt_cfg.broker.address.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.broker.address.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);
    /* The last argument may be used to pass data to the event handler, in this example mqtt_event_handler */
    esp_mqtt_client_register_event(client, ESP_EVENT_ANY_ID, mqtt_event_handler, NULL);
    esp_mqtt_client_start(client);
}

void app_main(void)
{
    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_BASE", ESP_LOG_VERBOSE);
    esp_log_level_set("esp-tls", 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());
    ESP_ERROR_CHECK(esp_netif_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();
}

Ohm
  • 21
  • 4
  • Hi @Ohm, welcome to Stack Overflow. Please edit the question to include a [minimal, reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) - that is, the smallest complete program - that demonstrates your problem. Describing code isn't helpful, we need to see the actual code that you're using. – romkey Oct 10 '22 at 05:10
  • If you are running your own AP on another ESP32 how is that device connected to the internet? A quick look at the code implies that is just creates a closed network, (internet access will be needed to 1) resolve `mqtt.eclipseprojects.io` and then 2) to connect to that broker. – hardillb Oct 10 '22 at 07:20
  • @hardillb now one ESP32 is running in [APSTA-mode](https://github.com/nopnop2002/esp-idf-wifi-apsta) so it has internet access and with other I am trying to use `protocol/mqtt/tcp` example but still the error is same. How can I resolve `mqtt.eclipseprojects.io` part that you mentioned? Is It related to mosqutto configuration in my laptop? of mqtt configuration in `protocol/mqtt/tcp`? – Ohm Oct 10 '22 at 13:31
  • @romkey thanks for the suggestions, I edited the question accordingly – Ohm Oct 10 '22 at 13:45
  • @Ohm Please don't link to code. Stack Overflow is a social Q&A site, so we ask that code be included in the question. This is also part of why we ask that it be minimal, to keep it brief and focussed. External links to code can stop working and are not searchable, so they don't help anyone else. Please edit your question to *include* your actual code and not the example it's based on. – romkey Oct 10 '22 at 18:09

0 Answers0