cannot connect esp32 to mqtt broker

Hi,

I am pretty new to Arduino and coding etc.

I have been trying to send data from an accelerometer via mqtt.

But whenever I use a different host address then “test.mosquitto.org” it doesn’t want to connect and gives me the following message:

“Attempting MQTT connection…failed, rc=-2 try again in 5 seconds”

Everything seems to be working on the side of the mqtt broker/client.

what am I doing wrong?
And how can it be fixed?

Any help is really appreciated.

esp32_mqqt_test.ino (5.36 KB)

What IP address does your ESP32 get?

How sure are you of the address of the broker?

thanks for the quick reply,

I am not quite sure what you mean with "What ip address does your esp32 get?"

I am fairly sure of the broker address(not 100%), since I have been able to send messages to MQTT explorer using this address.

mosquitto_sub_test.PNG

mosquitto_sub_test.PNG

Your wifi client is getting an IP address from somewhere - your router I expect. What is it?

the IP address of the esp32 is 192.168.1.119

Show your code.

Use MQTT.fx to make a connection the the Broker. Using MQTT.fx is a lot easier to find connection issues then using the Arduino IDE.

Here is some excellent code for an ESP32 that has maintained a connection since Feb 2020:

/*
   Project, use solar cells to generate power
   2/2/2020

*/
#include <WiFi.h>
#include <PubSubClient.h>
#include "certs.h"
#include "sdkconfig.h"
#include "esp_system.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/timers.h"
#include "freertos/event_groups.h"
//#include "esp_sleep.h"
#include <SPI.h>
#include <Adafruit_Sensor.h>
#include "Adafruit_BME680.h"
////
#define evtDoMQTTwd          ( 1 << 1 )
EventGroupHandle_t eg; // variable for the event group handle
////
WiFiClient wifiClient;
PubSubClient MQTTclient(mqtt_server, mqtt_port, wifiClient);
//////
Adafruit_BME680 bme( GPIO_NUM_5 );
///
/*
   This semaphore is used to stop or prevent a publish from happening during client.loop()
*/
SemaphoreHandle_t sema_MQTT_KeepAlive;
SemaphoreHandle_t sema_mqttOK; // protects the int mqttOK
////
int mqttOK = 0; // stores a count value that is used to cause an esp reset 
////
/*
 * A single subject has been scribed to, the mqtt broker sends out "OK" messages if the client receives an OK message the mqttOK value is set back to zero
 */
void IRAM_ATTR mqttCallback(char* topic, byte * payload, unsigned int length)
{
  xSemaphoreTake( sema_mqttOK, portMAX_DELAY );
  mqttOK = 0;
  xSemaphoreGive( sema_mqttOK );
} // void mqttCallback(char* topic, byte* payload, unsigned int length)
////
// interrupt service routine for WiFi events put into IRAM
void IRAM_ATTR WiFiEvent(WiFiEvent_t event)
{
  switch (event) {
    case SYSTEM_EVENT_STA_CONNECTED:
      break;
    case SYSTEM_EVENT_STA_DISCONNECTED:
      log_i("Disconnected from WiFi access point");
      break;
    case SYSTEM_EVENT_AP_STADISCONNECTED:
      log_i("WiFi client disconnected");
      break;
    default: break;
  }
} // void IRAM_ATTR WiFiEvent(WiFiEvent_t event)
////
////
void setup()
{
  sema_mqttOK = xSemaphoreCreateBinary();
  xSemaphoreGive( sema_mqttOK );
  eg = xEventGroupCreate(); // get an event group handle
  xTaskCreatePinnedToCore( MQTTkeepalive, "MQTTkeepalive", 20000, NULL, 5, NULL, 1 );
  xTaskCreatePinnedToCore( fDoBME, "fDoBME", 20000, NULL, 3, NULL, 1 ); // assigned to core
  xTaskCreatePinnedToCore( fmqttWatchDog, "fmqttWatchDog", 3000, NULL, 3, NULL, 1 ); // assign all to core 1
} //void setup()
////
////
void fmqttWatchDog( void * paramater )
{
  int maxNonMQTTresponse = 20;
  for (;;)
  {
    xEventGroupWaitBits (eg, evtDoMQTTwd, pdTRUE, pdTRUE, portMAX_DELAY );
    xSemaphoreTake( sema_mqttOK, portMAX_DELAY );
    mqttOK++;
    xSemaphoreGive( sema_mqttOK );
    if ( mqttOK >= maxNonMQTTresponse )
    {
      ESP.restart();
    }
  }
  vTaskDelete( NULL );
} //void fmqttWatchDog( void * paramater )
////
void connectToMQTT()
{
  MQTTclient.setKeepAlive( 90 ); // needs be made before connecting
  // create client ID from mac address
  byte mac[5];
  WiFi.macAddress(mac); // get mac address
  String clientID = String(mac[0]) + String(mac[4]) ; // use mac address to create clientID
  while ( !MQTTclient.connected() )
  {
    // boolean connect(const char* id, const char* user, const char* pass, const char* willTopic, uint8_t willQos, boolean willRetain, const char* willMessage);
    MQTTclient.connect( clientID.c_str(), mqtt_username, mqtt_password, NULL , 1, true, NULL );
    vTaskDelay( 250 );
  }
  MQTTclient.setCallback( mqttCallback );
  MQTTclient.subscribe( topicOK );
  log_i("MQTT Connected");
} // void connectToMQTT()
////
void fDoBME ( void *pvParameters )
{
  if (!bme.begin()) {
    log_i("Could not find a valid BME680 sensor, check wiring!");
    while (1);
  }
  // Set up oversampling and filter initialization
  bme.setTemperatureOversampling(BME680_OS_8X);
  bme.setHumidityOversampling(BME680_OS_2X);
  bme.setPressureOversampling(BME680_OS_4X);
  bme.setIIRFilterSize(BME680_FILTER_SIZE_3);
  bme.setGasHeater(320, 150); // 320*C for 150 ms
  float fTemperature = 0.0f;
  float fPressure = 0.0f;
  float fHumidity = 0.0f;
  uint32_t iGasResistance = 0;
  TickType_t DelayTime = 1000 * 30;
  //wait for a mqtt connection
  while ( !MQTTclient.connected() )
  {
    vTaskDelay( 250 );
  }
  for ( ;; )
  {
    fTemperature = bme.readTemperature();
    fTemperature = (fTemperature * 1.8f) + 32.0f; // (Celsius x 1.8) + 32
    fPressure = bme.readPressure();
    fPressure = fPressure / 133.3223684f; //converts to mmHg
    fHumidity = bme.readHumidity();
    iGasResistance = bme.readGas();
    xSemaphoreTake( sema_MQTT_KeepAlive, portMAX_DELAY ); // whiles MQTTlient.loop() is running no other mqtt operations should be in process
    log_i( "Temperature %f C, Pressure %f mmHg, Humidity %f, gasResistance %d", fTemperature, fPressure, fHumidity, iGasResistance );
    MQTTclient.publish( topicOutsideTemp, String(fTemperature).c_str() );
    vTaskDelay( 5 ); // gives the Raspberry Pi 4 time to receive the message and process
    MQTTclient.publish( topicOutsideHumidity, String(fHumidity).c_str() );
    vTaskDelay( 5 ); // no delay and RPi is still processing previous message
    MQTTclient.publish( topicOutsideGasResistance, String(iGasResistance).c_str() );
    vTaskDelay( 5 );
    MQTTclient.publish( topicOutsidePressure, String(fPressure).c_str() );
    vTaskDelay( 5 );
    xSemaphoreGive( sema_MQTT_KeepAlive );
    xEventGroupSetBits( eg, evtDoMQTTwd );
    vTaskDelay( DelayTime );
  } // for loop
  vTaskDelete ( NULL );
} // void fDoBME ( void *pvParameters )
////
/*
    Important to not set vTaskDelay to less then 10. Errors begin to develop with the MQTT and network connection.
    makes the initial wifi/mqtt connection and works to keeps those connections open.
*/
void MQTTkeepalive( void *pvParameters )
{
  sema_MQTT_KeepAlive   = xSemaphoreCreateBinary();
  xSemaphoreGive( sema_MQTT_KeepAlive ); // found keep alive can mess with a publish, stop keep alive during publish
  // setting must be set before a mqtt connection is made
  MQTTclient.setKeepAlive( 90 ); // setting keep alive to 90 seconds makes for a very reliable connection, must be set before the 1st connection is made.
  for (;;)
  {
    //check for a is-connected and if the WiFi 'thinks' its connected, found checking on both is more realible than just a single check
    if ( (wifiClient.connected()) && (WiFi.status() == WL_CONNECTED) )
    {
      xSemaphoreTake( sema_MQTT_KeepAlive, portMAX_DELAY ); // whiles MQTTlient.loop() is running no other mqtt operations should be in process
      MQTTclient.loop();
      xSemaphoreGive( sema_MQTT_KeepAlive );
    }
    else {
      log_i( "MQTT keep alive found MQTT status %s WiFi status %s", String(wifiClient.connected()), String(WiFi.status()) );
      if ( !(wifiClient.connected()) || !(WiFi.status() == WL_CONNECTED) )
      {
        connectToWiFi();
      }
      connectToMQTT();
    }
    vTaskDelay( 250 ); //task runs approx every 250 mS
  }
  vTaskDelete ( NULL );
}
////
void connectToWiFi()
{
  int TryCount = 0;
  //log_i( "connect to wifi" );
  while ( WiFi.status() != WL_CONNECTED )
  {
    TryCount++;
    WiFi.disconnect();
    WiFi.begin( SSID, PASSWORD );
    vTaskDelay( 4000 );
    if ( TryCount == 10 )
    {
      ESP.restart();
    }
  }
  WiFi.onEvent( WiFiEvent );
} // void connectToWiFi()
////
void loop() {}
////

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.