About This Project
This project will read temperature and humidity from a DHT11 or DHT22 sensor and send the values to Cayenne using MQTT. The python MQTT client and Adafruit DHT sensor library will need to be installed for this script to run. Install the MQTT client using "sudo pip install paho-mqtt". Install the Adafruit library using the commands below:
sudo apt-get install build-essential python-dev python-openssl
git clone https://github.com/adafruit/Adafruit_Python_DHT.git
sudo python setup.py install
import paho.mqtt.client as mqtt
time.sleep(30) #Sleep to allow wireless to connect before starting MQTT
username = "MQTT Username From Dashboard"
password = "MQTT Passsword From Dashboard"
clientid = "MQTT Client ID From Dashboard"
mqttc = mqtt.Client(client_id=clientid)
mqttc.connect("mqtt.mydevices.com", port=1883, keepalive=60)
topic_dht11_temp = "v1/" + username + "/things/" + clientid + "/data/1"
topic_dht11_humidity = "v1/" + username + "/things/" + clientid + "/data/2"
topic_dht22_temp = "v1/" + username + "/things/" + clientid + "/data/3"
topic_dht22_humidity = "v1/" + username + "/things/" + clientid + "/data/4"
humidity11, temp11 = Adafruit_DHT.read_retry(11, 17)
humidity22, temp22 = Adafruit_DHT.read_retry(22, 18)
if temp11 is not None:
temp11 = "temp,c=" + str(temp11)
mqttc.publish(topic_dht11_temp, payload=temp11, retain=True)
if humidity11 is not None:
humidity11 = "rel_hum,p=" + str(humidity11)
mqttc.publish(topic_dht11_humidity, payload=humidity11, retain=True)
if temp22 is not None:
temp22 = "temp,c=" + str(temp22)
mqttc.publish(topic_dht22_temp, payload=temp22, retain=True)
if humidity22 is not None:
humidity22 = "rel_hum,p=" + str(humidity22)
mqttc.publish(topic_dht22_humidity, payload=humidity22, retain=True)
except (EOFError, SystemExit, KeyboardInterrupt):
Save this file to /home/pi/python/tempsensor.py and fill in your username, password, and client id wherever required (lines 8, 9, 12, 13, 14, 15). You can also delete the DHT11 or DHT22 lines based on which sensor you are using or add additional lines to check more than 1 sensor. The topic_dht lines will all need unique channels, so be sure the last digit in the string is unique "v1/username/things/clientid/data/ 1 "
For testing just run the file with "python /home/pi/python/tempsensor.py". After it is working correctly add the widget to the dashboard permanently by clicking the + in the upper right hand, then add the python file to your crontab with "sudo crontab -e" then type in "@reboot python /home/pi/python/tempsensor.py &" and save. Reboot and you should see the values populate on your MQTT dashboard.