Trouble connecting Esp8266 with MQTT

Hi,
I’m new to home assistant, but I’ve been playing around with Arduino / ESP8266 for a couple years now.

I am trying to use MQTT to toggle On/Off a led on the Esp8266.
It seems like I’m having trouble connecting to the Mosquitto broker.

This is the sketch I am using to connect

#include <ESP8266WiFi.h>
#include <PubSubClient.h>

const char* _SSID = "Phantom";
const char* _Password = "**************";
const char* mqtt_server = "192.168.0.16";
const char* mqtt_user = "MQTT";
const char* mqtt_password = "**********";

WiFiClient espClient;
PubSubClient client(espClient);


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

  // Switch on the LED if an 1 was received as first character
  if ((char)payload[0] == '1') 
  {
    digitalWrite(LED_BUILTIN, LOW);   // Turn the LED on (Note that LOW is the voltage level
    // but actually the LED is on; this is because
    // it is active low on the ESP-01)
  } else 
  {
    digitalWrite(LED_BUILTIN, HIGH);  // Turn the LED off by making the voltage HIGH
  }
}

void setup_wifi() 
{

  // We start by connecting to a WiFi network
  Serial.println();
  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 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()), mqtt_user, mqtt_password) 
    {
      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();

  pinMode(LED_BUILTIN, OUTPUT);    // Initialize the LED_BUILTIN pin as an output

  
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
}


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

}

My Serial monitor is spamming the message

Attempting MQTT connection…connected

meaning it’s passing the line if (client.connect(clientId.c_str()), mqtt_user, mqtt_password)

but then in the main loop client.connected() returns false and try to reconnect every iteration of the loop

Also If I check the logs from Mosquitto I can see this error message:

2022-10-15 16:48:03: New connection from 192.168.0.184:58658 on port 1883.
error: received null username or password for unpwd check

My MQTT user looks like this:
image

And my my configuration file looks like this:


# Loads default set of integrations. Do not remove.
default_config:


# MQTT broker
mqtt:
  light:
    - name: "EspLight"
      command_topic: "home/ESPTest/light"
      state_topic: "home/ESPTest/status"
      payload_on: "0"
      payload_off: "1"
      retain: true


# Text to speech
tts:
  - platform: google_translate

automation: !include automations.yaml
script: !include scripts.yaml
scene: !include scenes.yaml

Anyone able to help? I am running out of ideas…

Turns out I was able to make it work using a different way of declaring the client and connecting in the code.

The mqtt_esp8266 example doesn’t work, but the one in mqtt_auth example does work.

basically had to declare the client like so:

WiFiClient espClient;
IPAddress server(192, 168, 0, xxx);
PubSubClient client(server, 1883, callback, espClient);

and call the connect method in the setup()

client.connect("arduinoClient", mqtt_user, mqtt_password)