MQTT OpenHab ESP8266

Hi Guys,

I’m new to OpenHab, i switched from home assistant to here. But i have a problem, and it’s an awfull one.

I’m trying to get the MQTT broker to work, i’m using OpenHabian for this. It is installed, and working fine i think. But when i try to get the ESP8266 to connect to it i keep getting an error RC=5 (MQTT_CONNECT_UNAUTHORIZED ). What can i do to solve this?

#include <ESP8266WiFi.h>
#include <DHT.h>
#include <PubSubClient.h>
#include <ESP8266mDNS.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>
#include <ArduinoJson.h>

/************ WIFI and MQTT INFORMATION (CHANGE THESE FOR YOUR SETUP) ******************/
#define wifi_ssid "###" //type your WIFI information inside the quotes
#define wifi_password "###"
#define mqtt_server "###" 
#define mqtt_user "openhabian"
#define mqtt_password "###!"
#define mqtt_port 1883

/**************************** PIN DEFINITIONS ********************************************/
#define DHTPIN    D7
#define DHTTYPE   DHT22
long previousMillis = 0;      // Timer loop from http://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
long interval = 60000;        //
String temp_str; //see last code block below use these to convert the float that you get back from DHT to a string =str
String hum_str;
char temp[50];
char hum[50];
long lastMsg = 0;
char msg[50];
int value = 0;


WiFiClient OpenHab;
PubSubClient client(OpenHab);
DHT dht(DHTPIN, DHTTYPE);

/********************************** START SETUP WIFI*****************************************/
void setup_wifi() {

  delay(10);
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(wifi_ssid);

  WiFi.mode(WIFI_STA);
  WiFi.begin(wifi_ssid, wifi_password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

/****reset***/
void software_Reset() // Restarts program from beginning but does not reset the peripherals and registers
{
  Serial.print("resetting");
  ESP.reset();
}

/********************************** START SETUP*****************************************/
void setup() {

  Serial.begin(9600);

  pinMode(DHTPIN, INPUT);

  Serial.begin(9600);
  delay(10);

  setup_wifi();

  client.setServer(mqtt_server, mqtt_port);
}

/**************98769879879******************** START SEND STATE*****************************************/
/*
   Calculate Heat Index value AKA "Real Feel"
   NOAA heat index calculations taken from
   http://www.wpc.ncep.noaa.gov/html/heatindex_equation.shtml
  float calculateHeatIndex(float humidity, float temp) {
   float heatIndex= 0;
   if (temp >= 80) {
     heatIndex = -42.379 + 2.04901523*temp + 10.14333127*humidity;
     heatIndex = heatIndex - .22475541*temp*humidity - .00683783*temp*temp;
     heatIndex = heatIndex - .05481717*humidity*humidity + .00122874*temp*temp*humidity;
     heatIndex = heatIndex + .00085282*temp*humidity*humidity - .00000199*temp*temp*humidity*humidity;
   } else {
      heatIndex = 0.5 * (temp + 61.0 + ((temp - 68.0)*1.2) + (humidity * 0.094));
   }

   if (humidity < 13 && 80 <= temp <= 112) {
      float adjustment = ((13-humidity)/4) * sqrt((17-abs(temp-95.))/17);
      heatIndex = heatIndex - adjustment;
   }

  return heatIndex;
  }
*/

/**** Reconnect ***/
void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect("OpenHab")) {
      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);
    }
  }
}



/********************************** START MAIN LOOP***************************************/
void loop()   
{
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
delay(2000);
//this is where you get the data from the sensor

  float humidity = dht.readHumidity(); 
  float temperature = dht.readTemperature();

//Using Serial print to debug
  Serial.print("\n\n");
  Serial.print("Luchtvochtigheid in %");
  Serial.print(humidity, 1);
  Serial.print("\t\t");
    Serial.print("Temperatuur in C");
  Serial.print(temperature, 1);
  Serial.print("\n");

 
//counter for the messages, see if I am missing any on the Mqtt broker
  
  long now = millis(); 
  if (now - lastMsg > 2000) {
    lastMsg = now;
    ++value;
    
//Preparing for mqtt send

    temp_str = String(temperature); //converting ftemp (the float variable above) to a string 
    temp_str.toCharArray(temp, temp_str.length() + 1); //packaging up the data to publish to mqtt whoa...

    hum_str = String(humidity); //converting Humidity (the float variable above) to a string
    hum_str.toCharArray(hum, hum_str.length() + 1); //packaging up the data to publish to mqtt whoa...

    Serial.print("Publish message: ");//all of these Serial prints are to help with debuging
    Serial.print("\n");
    
    client.publish("Algemeen/Temperatuur", temp); //money shot
    client.publish("Algemeen/Luchtvochtigheid", hum);
  }

}

This is my code for the ESP. it worked with Home Assistant, but just not with this one.

My mqtt.cfg is here.

#
# Define your MQTT broker connections here for use in the MQTT Binding or MQTT
# Persistence bundles. Replace <broker> with an ID you choose.
#

# URL to the MQTT broker, e.g. tcp://localhost:1883 or ssl://localhost:8883
OpenHab.url=tcp://localhost:1883

# Optional. Client id (max 23 chars) to use when connecting to the broker.
# If not provided a default one is generated.
OpenHab.clientId=OpenHab

# Optional. User id to authenticate with the broker.
OpenHab.user=openhabian

# Optional. Password to authenticate with the broker.
OpenHab.pwd=###

Thx for the help guys

Since all you have is a DHT22 I would recommend using something like ESP Easy. It does everything this code does with a nice web interface and other features.

That being said, I notice there is a mqtt user and password. What I don’t see is an MQTT client ID. That might be a problem, particularly if there is more than one client trying to use the same client id.

But it seems more likely you have a typo in one of the password fields preventing authentication.

What do you see in Mosquitto’s log when the ESP tries to connect?

Thank you for the answer!

Indeed, that web interface is nice. But i want to do more with it.

I used the exame same code as i previous used, for home assistant and that worked fine…

So i have no clue what i’m doing wrong…

The difference is that the Mosquitto Broker is probably configured differently. And that is where you need to be looking, in addition to any sort of logging you can get out of the ESP MQTT library, to see why it is refusing the connection.

Just skimming your esp8266 sketch. I can see where you define some variables to hold mqtt username and password, but I can’t see where you send it to the broker you’re trying to connect to

Your are using the same MQTT clientId for your esp and OH, change one of them

Thanks guys, it is fixed. There was a fault in the code. I used a different code what i found online.

You can also test it, and see it in the arduino serial monitor.

#include <ESP8266WiFi.h>
#include <PubSubClient.h>
 
const char* ssid = "ssid";
const char* password =  "pass";
const char* mqttServer = "ip";
const int mqttPort = 1883;
const char* mqttUser = "mqqt";
const char* mqttPassword = "mqttpass!";
 
WiFiClient espClient;
PubSubClient client(espClient);
 
void setup() {
 
  Serial.begin(9600);
 
  WiFi.begin(ssid, password);
 
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.println("Connecting to WiFi..");
  }
  Serial.println("Connected to the WiFi network");
 
  client.setServer(mqttServer, mqttPort);
  client.setCallback(callback);
 
  while (!client.connected()) {
    Serial.println("Connecting to MQTT...");
 
    if (client.connect("ESP8266Client", mqttUser, mqttPassword )) {
 
      Serial.println("connected");  
 
    } else {
 
      Serial.print("failed with state ");
      Serial.print(client.state());
      delay(2000);
 
    }
  }
 
  client.publish("esp/test", "Hello from ESP8266");
  client.subscribe("esp/test");
 
}
 
void callback(char* topic, byte* payload, unsigned int length) {
 
  Serial.print("Message arrived in topic: ");
  Serial.println(topic);
 
  Serial.print("Message:");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
 
  Serial.println();
  Serial.println("-----------------------");
 
}
 
void loop() {
  client.loop();
}```