Get MQTT/Mosquito to work with an ESP

Hey Folks,

I want to connect DIY-Arduino Projects to Homeassistant. (Not use ESPHome)

I installed MQTT and Mosquitto Broker, using the default configuration.

Now when i use a D1 Mini with this script:

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

// Replace with your Wi-Fi network credentials
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";

// Replace with your MQTT broker address
const char* mqtt_server = "your_MQTT_broker_IP_address";
const int mqtt_port = 1883;

// Replace with your MQTT username and password
const char* mqtt_user = "your_MQTT_username";
const char* mqtt_pass = "your_MQTT_password";

// Replace with your LED pin number
const int ledPin = D1;

WiFiClient espClient;
PubSubClient client(espClient);

void setup() {
  Serial.begin(9600);

  // Connect to Wi-Fi network
  WiFi.begin(ssid, password);
  Serial.print("Connecting to Wi-Fi");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("Connected to Wi-Fi");

  // Connect to MQTT broker
  client.setServer(mqtt_server, mqtt_port);
  while (!client.connected()) {
    Serial.print("Connecting to MQTT broker...");
    if (client.connect("WemosD1MiniClient", mqtt_user, mqtt_pass)) {
      Serial.println("connected");
      client.subscribe("homeassistant/led");
    } else {
      Serial.print("failed with state ");
      Serial.print(client.state());
      delay(2000);
    }
  }

  // Set LED pin as output
  pinMode(ledPin, OUTPUT);
}

void loop() {
  client.loop();
}

void callback(char* topic, byte* message, unsigned int length) {
  if (strcmp(topic, "homeassistant/led") == 0) {
    // Turn LED on or off based on incoming message
    if (strcmp((char*)message, "ON") == 0) {
      digitalWrite(ledPin, HIGH);
    } else if (strcmp((char*)message, "OFF") == 0) {
      digitalWrite(ledPin, LOW);
    }
  }
}

I got the Username and Password from Integrations → Mosquito Broker configure → Re-Configure MQTT.
Also tried it out without the login.

I get Connecting to MQTT broker…failed with state -2

I feel like i am missing out on something very obvious…

  1. Install a MQTT tool like https://mqtt-explorer.com/ and see if that connects to Mosquitto.
    This is a great way of seeing how MQTT really works, and maintenance like removing retained configuration messages.
  2. Can I suggest a walk-though of all MQTT settings including details of HASS discovery?:

There’s a few threads on creating custom MQTT clients using arduino (although my own experience is using Paho MQTT in Python on a RPiZero.)

If this helps, :heart: this post!