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