I can't connect mqtt broker to eps32 board

Hello,
I have an mqtt broker mosquitto running on localhost on my pc.
I have some external testing tools installed that can access my broker through ip 172.18.48.1
and my broker it's working, i can subscribe and publish to it.

Now I am trying to connect an ESP32 board, with the code below:

const char* ssid = "xxxxx";;
const char* password = "xxxxx";

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

const char* mqtt_server = "172.18.48.1";

const char* topic = "1";

WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;

void setup_wifi() {

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

  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...");
    // Create a random client ID
    String clientId = "ESP8266Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str())) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      client.publish("outTopic", "hello world");
      // ... and resubscribe
      client.subscribe("inTopic");
    } 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() {
  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
}

void loop() {

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

  long now = millis();
  if (now - lastMsg > 1000) {
    lastMsg = now;
    value = analogRead(A0);
    if (value > 4000) {
      value = 0;
    }
    else
    {
      value = 1;
    }
    
    snprintf (msg, 50, "hello world #%ld", value);
    Serial.print("Publish message: ");
    Serial.println(msg);

    snprintf (msg, 50, "%ld", value);
    client.publish(topic, msg);
  }
}

I can connect the board to wi fi, but when i try to run to connect to ip
"172.18.48.1", i receive error "Attempting MQTT connection...failed, rc=-2 try again in 5 seconds
". When I switch mqtt_server to a public broker like "broker.mqtt-dashboard.com" it works.

I'm sure I'm missing something, I have no knowledge of networking and I assume the problem is somewhere there, but I have no idea what and how to make it work.

Instead of using the IP address did you try using the computer name?

in checking for client connected do you test to see if WiFi is connected?

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

If no WiFi connection then no MQTT connection.

here is how I run client loop

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

notice a check for WiFi is done before doing the MQTT thing.

long now = millis();

will become an issue.

unsigned long now = millis();

is less of an issue.

here

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

the code assumes a good WiFi connection and a MQTT connection was made before running client.loop().

Yes, I specified that board is able to connect to wifi

Good luck.

This external tools are in other device / PC?

Maybe the problem is the firewall.

Check the firewall inbound rules then look in the mosquitto.conf file to see how the
# Listeners
section has been configured.

If someone else installed the Mosquitto instance, and it currently allows connections from one or more other machines then it is likely that they have already modified the config to allow some degree of outside connectivity. My guess is that the IP address of your ESP32 is outside the currently defined 'allowed' range.

Hello, thanks for reply. This is the content from mosquitto config file :

listener 1883
allow_anonymous true
log_type error
log_type warning
log_type notice
log_type information
connection_messages true
log_timestamp true
log_dest file C:\Program Files\mosquitto\mosquitto.log

I have created inbound rule in firewall to allow port 1883 connections

Install Wireshark. Filter on port 1883.
If you see no inbound traffic from the ESP32 then the communication problem is elsewhere.

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