MQTT and DHT22

@Dee Are the pi’s reporting their sensor data to the mosquito mqtt broker? You should be able to use a mqtt client, and subscribe to the topic, and see your sensor values. If this is not setup, that’s really your first step. Let me know if you need a hand with it.

I’m not sure how to set up the MQTT to report the sensors to the broker. I have watched videos and read tutorials I’m just not understanding what to put where. I have set up a test topic and tested (published) on all the PI’s and on HA so I know it works. If you can help me with setting up the topic. that would help me to understand it better. Thank you

You need a separate program - a client - to publish your data to the mqtt broker.

Something like https://github.com/sumnerboy12/mqtt-gpio-monitor will probably do the job.

Alternatively, you could adapt your existing program to send data to the broker.

@gpbenton ok I got mqtt-gpio-monitor, looked at and changed a few things in the ini.example file to match my configuration, but don’t see anything for what kind of sensors I’m using. where do i go from here Thanks

If you hunt around, you may be able to find something that does exactly what you want, otherwise you will need to do some coding yourself. The DHT22 seems fairly popular though, so someone may well have done this before. Try checking on the raspberry pi forums.

@Dee Install DHT22 library as described here: https://learn.adafruit.com/dht-humidity-sensing-on-raspberry-pi-with-gdocs-logging/software-install-updated . If you need, follow the wiring diagram to wire your DHT22 sensor correctly. In my case DHT22 was connected to GPIO23 in RPi. I use this code to send MQTT data to my MQTT broker (in my case it was 192.128.0.111 at port 1883). Also remember to install pip first and then “sudo pip install paho-mqtt”

#!/usr/bin/python

# -*- coding: utf-8 -*-

# Import required Python libraries
import paho.mqtt.client as mqtt
import pigpio
import time
import DHT22

# Define GPIO to use on Pi
GPIO_PIR = 23

print "Temperature Module Test (CTRL-C to exit)"

# Set pin as input
pi=pigpio.pi()
s=DHT22.sensor(pi,GPIO_PIR)

lastpubtemp=0.0
lastpubhumi=0.0

def checkBound(new, prev, maxdiff):
  if ((new < (prev - maxdiff)) or (new > (prev + maxdiff)) ):
    result = True
  else:
    result = False
  return result

try:

  #print "  Ready"
  mqttc = mqtt.Client()
  mqttc.connect("192.168.0.111", 1883)
  #mqttc.loop_start()

  # Loop until users quits with CTRL-C
  while True :

    s.trigger()
    #print('{:3.2f}'.format(s.temperature()/1.))
    temp_temp=(s.temperature()/1.)
    #print('{:3.2f}'.format(temp_temp))
    temp_humi=(s.humidity()/1.)
    #print('{:3.2f}'.format(temp_humi))
    #print "T:%3.2f TD:%3.2f H:%3.2f HD:%3.2f" % (temp_temp, abs(lastpubtemp-tem
p_temp), temp_humi, abs(lastpubhumi-temp_humi))
    #if ((abs(lastpubtemp-temp_temp) >= 0.1) and (temp_temp > 0.0)):
    if (checkBound(temp_temp,lastpubtemp,0.1) and (temp_temp > 0.0)):
      mqttc.publish("home/temperature", '{:3.2f}'.format(temp_temp), qos=0, retain=True )
      #print "PUB: T:%3.2f TD:%3.2f" % (temp_temp, abs(lastpubtemp-temp_temp))
      lastpubtemp=temp_temp
    #if ((abs(lastpubhumi-temp_humi) >= 0.1) and (temp_humi > 0.0)):
    if (checkBound(temp_humi,lastpubhumi,0.1) and (temp_humi > 0.0)):
      mqttc.publish("home/humidity", '{:3.2f}'.format(temp_humi), qos=0, retain=True )
      #print "PUB: H:%3.2f HD:%3.2f" % (temp_humi, abs(lastpubhumi-temp_humi))
      lastpubhumi=temp_humi
    mqttc.loop()

    # Wait for 10 seconds
    time.sleep(10)

except KeyboardInterrupt:
  #mqttc.loop_stop()
  mqttc.disconnect()
  s.cancel()
  #print "  Quit"

Un-comment a few lines to see debug values.

Edit: Forget to mention I also have pigpio service installed from http://abyz.co.uk/rpi/pigpio/index.html

@Dee Here’s the basic flow of how things should work.
DHT22-> read values-> publish values to broker topic(s).
HA subscribes to broker/topic(s)-> loads values as sensors-> displays values.

The discussion and code above is referencing the first part. Once you can get the values published to the broker/topic the HA part is pretty simple, as HA is just a mqtt client, subscribing to the topics to read the values. For testing, you might benefit from installing a mqtt client on your computer, this will allow you to subscribe to the broker/topic(s) and read them directly, outside of HA. Checkout http://mqttfx.jfx4ee.org/ which works great…

I took a different approach, and used a ESP8266, combined with a DHT22. In the end, it’s a self contained package, a little smaller then a smoke detector, powered via usb. I’ve built 3, and placed them around my house. I’m still updating the document, but here’s a link to it on my website, in case you’re interested: http://morphx.net/doku.php?id=dht22-sensor

@debsahu I have had the dht22 running on the pi’s for over a year, with no problem. And I do have paho-mqtt installed, I set up the python script and ran it but got an ImportError: No module named DHT22 I’m thinking it’s Adafuit_DHT but changed that and go other Errors I think I’ve been working on this to long straight, I know I’m missing something Probably easy.

@xstrex I like your setup I have seen and read about the ESP8266 I may look into them might be better then tying up the Raspberry pi’s

@Dee I have DHT22.py in the same folder as the python script. This can be found here http://abyz.co.uk/rpi/pigpio/code/DHT22_py.zip

I have tons of ESP8266 based DHT22 sensors with PIR and I2C display in my home automation under $10 including housing and power supply. Let me know if you want me to share that Audrino IDE code.

@debsahu I have a user name and password on my mqtt broker do I need to add it to the script.

@xstrex and @debsahu what do you think of these for a first time ESP8622, I’m thinking of ordering them.

[ESP8622](Makerfocus 2pcs ESP8266 Module ESP-12E NodeMcu LUA WiFi Internet New Version Development Board https://www.amazon.com/dp/B01IK9GEQG/?&ref=flgs_it_share)

@Dee yes please add this line before mqttc.connect()

mqttc.username_pw_set(“username”, “password”)

With appropriate login details.

You can use any esp8266 board, I personally use Nodemcu 1.0 similar to one you posted but with a CP2102 USB serial chip. The one you posted has CH305 which is also fine, but a year or so ago it had a flaky driver for windows so people preferred the silicon labs chip.

@Dee As for which ESP8266 board to use, it really comes down to personal preference. I went with the HUZZAH board by Adafruit (https://www.adafruit.com/products/2471), it’s well documented on their site, and provides lots of instructions on how to get started with it. Plus their forum has tons of great resources in case you get stuck. I would however recommend getting a board without headers, as you’re probably only going to use a few pins, and the rest will just get in the way, but that’s entirely up to you.

Also keep in mind, however you decide to build these little guys, unless you’re using a breadboard with jumper wires, you’re going to have to have and use some basic soldering skills, and tools. If that’s not something you’re comfortable with, ya might want to get that under your belt first.

Another great resource for everything ESP8266 is this forum: http://www.esp8266.com/
You’ll find tons of projects, how-to’s, and code to help you get started. Here’s a project by Adafruit that’s very similar to the method i’m using, all you’d have to do is swap out their mqtt broker, for yours, plus it’s really well documented and might be a good starting point: https://learn.adafruit.com/home-automation-in-the-cloud-with-the-esp8266-and-adafruit-io

Thanks for all the help everyone I was able to get the temperatures and humidity published and subscribed to it. I haven’t got it setup in HA yet but, at least now I understand it a little better.

@xstrex, @debsahu I did order that ESP8622 board this morning, hope to have them in a few days. If you could share your Arduino IDE code that would be great.

Just to let you guys know I’m 58 yeas old, I bought my first RPI Sept. 2015 I own 8 now and have one Arduino UNO is been plugged in 2 times since I’ve had it. bought it for a Project, that I never finished. I have been into electronics all my life. my first Home Automation system was a x10 whole house system, I still have the switches and plugs. About 10 years ago I thought about learning linux, but my Bother talked me out of it (he had his on computer business) now I wish I would have done it. sorry for rambling anyways thanks again for all your help.

@Dee You’ve got about 20yrs on me, but i’m in the same boat. Been into electronics my whole life, and started with x10, then later switched to Insteon. Learning Linux is a big help, it will make working with HA a lot easier. I’m a Linux Admin by trade, so that helps a lot. But I’m sure if you ask any questions here, you’ll get the right answers. Let me know if I can help with anything.

That’s great that you got your temp/humidity published, getting it added to HA is pretty straight forward. You’ll need to add the mqtt config to your configuration.yaml file first, that will get HA talking to your broker. It’s documented here; https://home-assistant.io/components/mqtt/ As an example, here’s my config:

mqtt:
broker: 192.168.X.X
port: 1883
client_id: home-assistant
keepalive: 60

Once it’s added you’ll need to setup a sensor for each of the topics you want to display. One for temperature, another for humidity. This would also go into your configuration.yaml file. It’s documented here: https://home-assistant.io/components/sensor.mqtt/ Here’s and entry for mine:

  • platform: mqtt
    state_topic: ‘office/temp’
    name: ‘Office Temperature’
    unit_of_measurement: ‘°F’

After that, restart HA, and you should have the values displayed on the main states page (unless you’ve customized the UI with groups/view, if so you’ll need to add the sensor there).

As for the ESP8266 code, I’ve posted mine here: http://morphx.net/doku.php?id=dht22-sensor
Hope this helps, let me know if you have any other questions.

@xstrex I was able to get everything up and running good Thank you. One question, can I have the DHT22 and 2 ds18b20 sensors on the ESP8622

@Dee You should be able to, it looks like they use a single digital I/O pin. I’m thinking you could wire it up to one of the GPIO’s, there’s 9 in total. You’ll probably have to use a breadboard for common ground/vcc. Checkout the forum over at: http://www.esp8266.com/ for more info, just search for ds18b20.

@xstrex I received my ESP8266 boards in a few days ago. Question are you using a Windows computer to upload sketch? I’m getting an error on my Windows 7 pc. I am able to load the blinking test and a few that was default, I’m going to try Windows 10 machine today, It just seems like it my be a Windows problem.

Forgot to tell you I did download all the drivers the boards and the fills needed for the sketch. I am only trying a DHT22 test sketch for now until I see everything works.

The Error I get is about the board, is a file location Error, but not sure why when the other sketches work.

@Dee I used a Mac, but that doesn’t matter, it should work on any platform. Any chance you can post the error message you’re getting? Also, you’ll have to make sure you have the right libraries installed in your IDE. I’ll take a look at mine, and add a link to the required libraries (please give me a bit, still waking up). But the errors should help us figure it out.