Using mqtt from ESP to Openhab2

I think the main issue was the reset pin. Maybe I will try it with an other ESP-12E to confirm the results…

Hi guys.

I am having same errors about bad socket on MQTT

I just have installed an Openhabian image with Mosquitto and openhabgenerator.

I am looking to connect a device ESP8266 node MCU using ESP Easy V2.0

below you can see my logs, and attached the ESP easy screens.


ESPEasy ControllerMosquitto Log

ESPEasy Log


ESPEasy Log
1419823 : WD : Uptime 24 ConnectFailures 94 FreeMem 22768
1419823 : MQTT : Connection lost
1420934 : MQTT : Failed to connected to broker
1421456 : MQTT : Failed to connected to broker

Mosquitto Log
1504567388: Socket error on client , disconnecting.
1504567418: New connection from 192.168.7.128 on port 1883.

Mosquitto Status
[20:27:13] openhabian@CriaLabPi:~$ sudo systemctl status mosquitto

  • mosquitto.service - Mosquitto MQTT Broker
    Loaded: loaded (/lib/systemd/system/mosquitto.service; enabled)
    Active: active (running) since Sun 2017-09-03 21:54:50 -03; 22h ago
    Docs: man:mosquitto(8)
    https://mosquitto.org/
    Main PID: 453 (mosquitto)
    CGroup: /system.slice/mosquitto.service
    `-453 /usr/sbin/mosquitto -c /etc/mosquitto/mosquitto.conf

OpenHab2 items
GNU nano 2.2.6 File: /etc/openhab2/items/CriaLab.items

Group Home “CriaLab”
Group GF “GF” (Home)
Group FF “FF” (Home)
Group F2 “F2” (Home)

Group GF_Terrace “Terrace” (Home, GF)
Switch GF_Terrace_Light “Light” (GF_Terrace, Lights)

Have you fully tested your mqtt broker?
In one terminal window type
mosquitto_sub -d -t testTopic

and on another type
mosquitto_pub -d -t testTopic -m "Hello world!"
You should see “Hello world!” on the first terminal window.
This will tell you if the broker is working and connecting correctly.

good point.

the first keeps telling this:

Client mosqsub|29553-CriaLabPi sending CONNECT
Client mosqsub|29553-CriaLabPi received CONNACK
Connection Refused: not authorised.
Client mosqsub|29553-CriaLabPi sending CONNECT
Client mosqsub|29553-CriaLabPi received CONNACK
Connection Refused: not authorised.
Client mosqsub|29553-CriaLabPi sending CONNECT
Client mosqsub|29553-CriaLabPi received CONNACK
Connection Refused: not authorised.

the second terminal was this:

[20:36:05] openhabian@CriaLabPi:~$ mosquitto_pub -d -t testTopic -m "Hello world!"
Client mosqpub|29887-CriaLabPi sending CONNECT
Client mosqpub|29887-CriaLabPi received CONNACK
Connection Refused: not authorised.
Error: The connection was refused.
[20:36:13] openhabian@CriaLabPi:~$

Hi Rob, thank you for the useful information. Everything is working great with my mosquitto server, I can read all the messages from Mqtt.fx, my nodeMCU + DHT11 publishes everything to “sensor/temperature” and “sensor/humidity” but i cant see this on my openhub2 basic UI. I guess that the problem relays when i create the item. Right now i wrote this:

//1
Number Temperature “Temperature [%.1f]” {mqtt="<[broker:sensor/temperature:state:default]"}"

//2
Number Humidity “Humidity [%.1f%%] {mqtt=”<[broker:sensor/humidity:state:default]"}"

name of my broker: "broker"
ip address of the broker: "192.168.0.10"
port: 1883
clientid: "not set"
user: "not set"
pass: “not set”

Can you help me to write the right line in the Items file and the sitemap file? Thank you very much.

Hi Gonzalo
Not sure if you did a cut & paste but there is an extra quote mark " at the end of each line i.e. try

instead of

also your “Humidity” line is missing a quote mark " after the %]. I.e. should be %]".

If these corrections don’t fix it try
broker:/sensor
instead of

broker:sensor

Thanks for the catch. Now it looks like this:

But it still doesnt work. I tried without the “/” also. But when i do: mosquitto_sub -v -t ‘sensor/#’ i get all the information. I dont know whats wrong.

What’s the contents of your mqtt.cfg file - have you actually named your broker “broker”

Yes i did. This is my cfg file:


#
# 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
broker.url=tcp://192.168.0.10:1883

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

# Optional. True or false. If set to true, allows the use of clientId values
# up to 65535 characters long. Defaults to false.
# NOTE: clientId values longer than 23 characters may not be supported by all
# MQTT servers. Check the server documentation.
#<broker>.allowLongerClientIds=false

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

# Optional. Password to authenticate with the broker.
#mosquitto.pwd=espagnol300

# Optional. Set the quality of service level for sending messages to this broker.
# Possible values are 0 (Deliver at most once),1 (Deliver at least once) or 2
# (Deliver exactly once). Defaults to 0.
#<broker>.qos=<qos>

# Optional. True or false. Defines if the broker should retain the messages sent to
# it. Defaults to false.
#<broker>.retain=<retain>

# Optional. True or false. Defines if messages are published asynchronously or
# synchronously. Defaults to true.
#<broker>.async=<async>

# Optional. Defines the last will and testament that is sent when this client goes offline
# Format: topic:message:qos:retained <br/>
#<broker>.lwt=<last will definition>


Thanks.

The usual prime candidate for MQTT issues is that the OH->MQTT configuration is often not set up right.

Do you have a username & password configured for MQTT - you have details in the config file, but the lines are commented out (with a # at the beginning).

I know, i prefered to leave it open to make it easier.

If you have run OH with those lines not commented out, it has probably cached your user credentials and is trying to authenticate to MQTT.

Commenting out the lines does not, unfortunately, not use the config, it just uses the last one defined!

You can run the following at the console to clear out the existing MQTT configuration, and restart OH, this will then read the new configuration from the .cfg file.

config:delete org.openhab.mqtt

Thanks for the reply. Now it works. I uncommented the lines for clientid, user and pass. I reload the code in my arduino using this credentials and now it works. Thank your very much for the help. One more question if i may:

My temperature/humidity looks like this:

How can i do to get real values? I got the code from another website. Its looks like this:

// Get ESP8266 going with Arduino IDE
// - https://github.com/esp8266/Arduino#installing-with-boards-manager
// Required libraries (sketch -> include library -> manage libraries)
// - PubSubClient by Nick ‘O Leary
// - DHT sensor library by Adafruit

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

#define wifi_ssid "xxxxxxxxx"
#define wifi_password "xxxxxxxx"

#define mqtt_server "192.168.0.10"
#define mqtt_user "openhabian"
#define mqtt_password "espagnol300"

#define humidity_topic "sensor/humidity"
#define temperature_topic "sensor/temperature"

#define DHTTYPE DHT22
#define DHTPIN  14

WiFiClient espClient;
PubSubClient client(espClient);
DHT dht(DHTPIN, DHTTYPE, 11); // 11 works fine for ESP8266

void setup() {
  Serial.begin(115200);
  dht.begin();
  setup_wifi();
  client.setServer(mqtt_server, 1883);
}

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

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

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    // If you do not want to use a username and password, change next line to
    // if (client.connect("ESP8266Client")) {
    if (client.connect("ESP8266Client", mqtt_user, mqtt_password)) {
      Serial.println("connected");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

bool checkBound(float newValue, float prevValue, float maxDiff) {
  return !isnan(newValue) &&
         (newValue < prevValue - maxDiff || newValue > prevValue + maxDiff);
}

long lastMsg = 0;
float temp = 0.0;
float hum = 0.0;
float diff = 1.0;

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

  long now = millis();
  if (now - lastMsg > 2000) {
    lastMsg = now;

    float newTemp = dht.readTemperature();
    float newHum = dht.readHumidity();

    if (checkBound(newTemp, temp, diff)) {
      temp = newTemp;
      Serial.print("New temperature:");
      Serial.println(String(temp).c_str());
      client.publish(temperature_topic, String(temp).c_str(), true);
    }

    if (checkBound(newHum, hum, diff)) {
      hum = newHum;
      Serial.print("New humidity:");
      Serial.println(String(hum).c_str());
      client.publish(humidity_topic, String(hum).c_str(), true);
    }
  }
}

Excellent :slight_smile:

OH will be saving/displaying the value sent from your ESP - my guess is that it is sending the wrong value in the first place - so you’ll need to have a look at the code going onto the ESP to figure out where this is going wrong :slight_smile: Is it printing the right value to the serial monitor, for example?

Yes, it is definitly the something wrong with the code. Or some other temperature unit that i would need to transform. But, does something looks wrong at a glance?

One of my friends (@Rob_Pope) did some working code to publish from an ESP with a DHT11 to MQTT, which you can find on his Github page here

I’ve successfully used this - you’ll just need to add in your MQTT authentication, IP address etc and amend the topic names - but this should work for you.

This will also report every 60 seconds - your code appears to only report if there’s a substantial change. I prefer having a known value every minute, and this can also be used as an indicator of whether the ESP is still running and publishing values.

Thank you very much. I will give it a try and I will report back. Thank you for all the help. Highly appreciated.

It is working perfectly. Thank you very much and thanks to @Rob_Pope for the code.

2 Likes

Its me again. I suddenly lost connection to the broker. Im monitoring it with MQTT.fx and the log file says:

2017-12-05 21:00:15,659  INFO --- MqttFX ClientModel             : Broker connection lost: Retrying...

I restart the raspberry pi with sudo restart, but it didnt connect. What can i do?. Thanks for the reply.

You probably just need to restart the Arduino. If it loses the connection to the broker for a period it will give up trying and need to be restarted. This could happen if you reboot the server or there is a network glitch.
You can also check in the log for info if you are using ESPEasy.