Issues connecting esp32 to mqtt broker

Hi all,
I am facing issues connecting my esp32 to hivemqtt broker.
It gives me the following error:

E(10968) MQTT_CLIENT: mqtt_message_receive: transport_read() error: errorno =128.
E(10968) MQTT_CLIENT: esp_mqtt_connect: mqtt_message_receive() return -1.
E(10978) MQTT_CLIENT: MQTT connect failed.

These are the credentials I have used.

static void mqtt_app_start(void)
{
    esp_mqtt_client_config_t mqtt_cfg = {
       // .host = "mqtt://broker.hivemq.com",
        .uri = "mqtt://b9**********************************7.s2.eu.hivemq.cloud:8883",
        .port = 8883,
        .username = "my_username",
        .password = "my_password",
        .client_id = "Client123",
       // .event_handle = "mqtt_event_handler",
        .disable_auto_reconnect = false,
        .lwt_qos = 0,
        //.transport = MQTT_TRANSPORT_OVER_TCP,       //choosing TCP over TLS/SSL
    };

    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);

    vTaskDelay(1000);

Hello @Tarun

Welcome to HiveMQ Community! Please use the code below as a reference. I have tested it on my NodeMCU ESP32 device and it worked like a charm! Give it a try on your ESP32 device and share the results.

#include <WiFi.h>  
#include <PubSubClient.h>
#include <WiFiClientSecure.h>

//---- WiFi settings
const char* ssid = "XXXXXXXXXX";
const char* password = "XXXXXXXXXX";

//---- HiveMQ Cloud Broker settings
const char* mqtt_server = "XXXXXXXXXX.s2.eu.hivemq.cloud"; // replace with your HiveMQ Cluster URL
const char* mqtt_username = "XXXXXXXXXX"; // replace with your Username
const char* mqtt_password = "XXXXXXXXXX"; // replace with your Password
const int mqtt_port = 8883;

WiFiClientSecure espClient;  
PubSubClient client(espClient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE (500)
char msg[MSG_BUFFER_SIZE];
int value = 0;

// HiveMQ Cloud Let's Encrypt CA certificate (hardcoded)
static const char *root_ca PROGMEM = R"EOF(
-----BEGIN CERTIFICATE-----
MIIFazCCA1Og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MA4GA1UdDwEB/wQEAwIBBjAPBgNV
HRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq
hkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL
ubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ
3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK
NFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5
ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur
TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC
jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc
oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq
4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA
mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d
emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=
-----END CERTIFICATE-----
)EOF";

void setup_wifi() {
  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  randomSeed(micros());

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();
}


void reconnect() {
  // Loop until we’re reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection… ");
    // MQTT client ID
    String clientId = "ESP32Client";
    // Attempt to connect
    if (client.connect(clientId.c_str(), mqtt_username, mqtt_password)) {
      Serial.println("connected!");
      // Once connected, publish an announcement…
      client.publish("testTopic", "Hello World!");
      // … and resubscribe
      client.subscribe("testTopic");
    } else {
      Serial.print("failed, rc = ");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void setup() {
  delay(500);
  // When opening the Serial Monitor, select 9600 Baud
  Serial.begin(9600);
  delay(500);

  setup_wifi();

  espClient.setCACert(root_ca);
  client.setServer(mqtt_server, mqtt_port);
  client.setCallback(callback);
}

void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();

  unsigned long now = millis();
  if (now - lastMsg > 2000) {
    lastMsg = now;
    ++value;
    snprintf (msg, MSG_BUFFER_SIZE, "Hello World! #%ld", value);
    Serial.print("Publish message: ");
    Serial.println(msg);
    client.publish("testTopic", msg);
  }
}

Kind regards,
Diego from HiveMQ Team

Hi Diego,
Thank you for replying, I appreciate your detailed instruction and references. However, I have a specific requirement to code in espidf for my project. If you have any suggestions on how to connect esp32 to Hive-MQTT broker without using certificate in espidf, I would greatly appreciate your help.
Thank you.

@Tarun

You’re welcome. Please be aware that HiveMQ Cloud only allows secure TLS connections. To establish a TLS connection, your client/device must trust the Certificate Authority (CA) that has issued the certificate to the HiveMQ Cloud server to which your client is attempting to connect (i.e. Let’s Encrypt).

Additionally, to establish a TLS connection to the HiveMQ Cloud, your client must enable and use the TLS protocol extension called “SNI” (Server Name Indication). This TLS extension provides the server’s hostname in the “Client Hello” TLS packet.

I’m not familiar with ESP-IDF framework and the only MQTT TLS example that I found was esp-idf/examples/protocols/mqtt/ssl/main/app_main.c at be06a6f5ffe36f9554cfc91fe2036e0fc85fea60 · espressif/esp-idf · GitHub I’m not sure if that helps with your project.

You might consider deploying HiveMQ Community Edition as an alternative, enabling you to establish connections without requiring TLS.

Kind regards,
Diego from HiveMQ Team

Hi Diego.
I was planing to connect hivemq broker to esp32(in esp-idf) as we connect it in Arduino ide using “'client.setInsecure()” function. Since, whichever IDE is being used it connect to same broker right.

Hi Diego,
I am trying to connect it using via secure TLS. Could you teel me how can I get the root certificate of my hivemqtt broker.

Hi @Tarun

The root certificate is hardcoded in the Arduino code that I shared previously but it also can be downloaded from https://letsencrypt.org/certs/isrgrootx1.pem . This will create a file isrgrootx1.pem which should be used as a “server certificate”.

Kind regards,
Diego from HiveMQ Team

Hi @Diego,
I am facing a new kind of error while connecting to hivemq. I am connecting to it via TCP and it’s a secure domain.

Controller: ESP-32 wrover

This the Log for the same

I (32615) MQTT_EXAMPLE: Other event id:7
E (32615) esp-tls: couldn't get hostname for :b9ff4eeb544e4ac18142a019bc399b43.s2.eu.hivemq.cloud: getaddrinfo() returns 202, addrinfo=0x0
E (32615) esp-tls: Failed to open new connection
E (32625) transport_base: Failed to open a new connection
E (32625) mqtt_client: Error transport connect
I (32635) MQTT_EXAMPLE: MQTT_EVENT_ERROR
E (32635) MQTT_EXAMPLE: Last error reported from esp-tls: 0x8001
I (32645) MQTT_EXAMPLE: Last errno string (Success)
I (32655) MQTT_EXAMPLE: MQTT_EVENT_DISCONNECTED
E (39035) mqtt_client: Client has not connected

This the code snippet Iam using

/**
 * MQTT Application: 
 * Date Created: 05-05-2024
 * Author : Tarun
*/
#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 "wifi_app.h"
#include "mqtt_client.h"
#include "mqtt_app.h"
#include "gpio_esp.h"
#include "ultrasonic.h"
#include "nvs_app.h"



static const char *TAG = "MQTT_EXAMPLE";
esp_mqtt_client_handle_t client;
char buffer[50];                           // buffer for subscribed data
uint8_t mac_id[20];
//string response_mqtt;
bool mqtt_connect_status = false;           // Flag to check connection to MQTT-broker

void stringcopy(char * st1, char * st2)         //st1 -> source || st2 -> destination
{
    int i = 0;
      for (i = 0; st1[i]!='\0'; i++)
      {
          st2[i] = st1[i];
      }
    st2[i] = '\0';
}

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);
    }
}

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");
        mqtt_connect_status = true;
        msg_id = esp_mqtt_client_subscribe(client, "my_topic1", 0);
        //ESP_LOGI(TAG, "sent subscribe successful, msg_id=%d", msg_id);
        
        msg_id = esp_mqtt_client_publish(client, "my_topic1", "vivid", 5, 0, 0);
        //ESP_LOGI(TAG, "sent publish successful, msg_id=%d", msg_id);
        break;
    case MQTT_EVENT_DISCONNECTED:
        ESP_LOGI(TAG, "MQTT_EVENT_DISCONNECTED");
        mqtt_connect_status = false;
        break;
    case MQTT_EVENT_SUBSCRIBED:
        //ESP_LOGI(TAG, "MQTT_EVENT_SUBSCRIBED, msg_id=%d", event->msg_id);
        // msg_id = esp_mqtt_client_publish(client, "my_topic1", i+1, 2, 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);
        strncpy(buffer,event->data,event->data_len);
        //stringcopy(event->data, buffer);
        if( strlen(buffer) == 0)
        {
            buffer[0] = '\0';       //
            //memset(buffer, 0, sizeof(buffer));    //setting whole string at "0"
        }
        //strncpy(buffer,event->data,event->data_len);    // Copying data into data buffer/ Need to find alternate the 
        printf("\nbuffer : %s\n", buffer);
        // val[] = 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;
    }
}

void mqtt_app_start(void)
{
    esp_mqtt_client_config_t mqtt_cfg = {               // MQTT broker configurations
        .uri = CONFIG_BROKER_URL,
        .username = "my_username",
        .password = "my_password",
        .client_id = "Tarun123",
    };
    client = esp_mqtt_client_init(&mqtt_cfg);
    /* The last argument may be used to pass data to the event handler, I am not passing any arguement as of now. */
  
    
    esp_mqtt_client_register_event(client, ESP_EVENT_ANY_ID, mqtt_event_handler, NULL);
    esp_mqtt_client_start(client);
}

Kindly, help me in this this quiet urgent and important for me.

Hello @Tarun

The error you’re encountering indicates an issue with DNS resolution when the ESP32 attempts to connect to HiveMQ Cloud. It seems your ESP32 device is unable to resolve the HiveMQ Cloud hostname to an IP address, preventing it from connecting to the broker.

esp-tls: couldn't get hostname for :b9ff4eeb544e4ac18142a019bc399b43.s2.eu.hivemq.cloud: getaddrinfo() returns 202, addrinfo=0x0

Ensure that the ESP32 is properly connected to a Wi-Fi network and that the DNS server assigned is functioning correctly.

Kind regards,
Diego from HiveMQ Team

After used the code your provided on top I got this:

Attempting MQTT connection… [835425][E][ssl_client.cpp:37] _handle_error(): [start_ssl_client():273]: (-30592) SSL - A fatal alert message was received from our peer
[835426][E][WiFiClientSecure.cpp:144] connect(): start_ssl_client: -30592
failed, rc = -2 try again in 5 seconds
Attempting MQTT connection… [841578][E][ssl_client.cpp:37] _handle_error(): [start_ssl_client():273]: (-30592) SSL - A fatal alert message was received from our peer
[841579][E][WiFiClientSecure.cpp:144] connect(): start_ssl_client: -30592
failed, rc = -2 try again in 5 seconds
Attempting MQTT connection… [847305][E][ssl_client.cpp:37

Note: I uploaded the certificate in

Client Certificate
Allow your clients to prove their identity and gain access to your cluster using digitally-signed certificates.

which results ACTIVE

The certificate I charged is:

-----BEGIN CERTIFICATE-----
MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw
TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh
cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4
WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu
ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY
MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc
h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+
0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK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bUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc
oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq
4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA
mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d
emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=
-----END CERTIFICATE-----

Any help would be kindly appreciated, thanks!

Hello @andyc

Sorry for the delay in answering here. Please share more details about your current environment.

  • Are you using Arduino IDE?
  • What are the results if you use the hardcoded certificate inside the code as I shared in the sample code?

Kind regards,
Diego from HiveMQ Team