Search code examples
c++arduinolocalhostesp8266mosquitto

MQTT connection through ESP01 8266


I'm trying to establish a connection with my m Mosquitto server through an ESP01 8266. I installed Mosquitto on my computer and started it with Brew.

The problem is that the ESP01 doesn't connect to the "localhost:1833" (that should be my Mosquitto address). I don't know what to do, am I missing something?

This line could be the problem? I didn't set a client name on NodeRed -------> if (mqttClient.connect("ESP8266Client"))

ESP sketch:

#include <ESP8266WiFi.h>
#include <PubSubClient.h>
    
const char* ssid         = "WifiNetworkname";
const char* password     = "password";
const char* mqttServer   = "localhost:1833";
const int   mqttPort     = 1883;
    
#define PUB_GPIO2_STATUS "state"
#define SUB_GPIO2_ACTION "state"
#define GPIO2_LED 2
     
WiFiClient wifiClient;
PubSubClient mqttClient(wifiClient);
     
void loop() {
  mqttClient.loop();
}
    
void initWifiStation() {
  WiFi.mode(WIFI_AP_STA);
  WiFi.begin(ssid, password);    
  Serial.print("\nConnecting to WiFi");
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);        
    Serial.print(".");
  }
  Serial.println(String("\nConnected to the WiFi network (") + ssid + ")" );
}
     
void initMQTTClient() {
  // Connecting to MQTT server
  mqttClient.setServer(mqttServer, mqttPort);
  while (!mqttClient.connected()) {
    Serial.println(String("Connecting to MQTT (") + mqttServer + ")...");
    if (mqttClient.connect("ESP8266Client")) {
      Serial.println("MQTT client connected");  
    } else {
      Serial.print("\nFailed with state ");
      Serial.println(mqttClient.state());
      if (WiFi.status() != WL_CONNECTED) {
        initWifiStation();
      }
      delay(2000);
    }
  }
    
  // Declare Pub/Sub topics
  mqttClient.publish(PUB_GPIO2_STATUS, "Hello");
  mqttClient.subscribe(SUB_GPIO2_ACTION);
}
    
void setup() {
  Serial.begin(115200);
  // GPIO2 is set OUTPUT
  pinMode(GPIO2_LED, OUTPUT);
  initWifiStation();
  initMQTTClient();
}

Solution

  • Localhost in the code on your ESP is the ESP itself. You are trying to connect from the ESP, to the ESP.

    Localhost always refers to "this computer", just like the IP address 127.0.0.1 does.

    "This computer" as seen from the code on the ESP is the ESP itself, and not the computer that is running the MQTT server.

    Assuming the syntax is otherwise correct: in the line const char* mqttServer = "localhost:1833"; you need to put in the IP address (or name) of the computer that runs your MQTT server instead of localhost. I don't know if you also need to change the port.