DHT11/DHT22 with Raspberry Pi

Some possible issues that could cause the device to go offline:

  1. mqttc.loop() should be called to process mqtt messages inside the main loop to keep the connection alive.
while True:
    try:
        mqttc.loop()
        humidity11, temp11 = Adafruit_DHT.read_retry(11, 17) #11 is the sensor type, 17 is the GPIO pin number
        humidity22, temp22 = Adafruit_DHT.read_retry(22, 18) #22 is the sensor type, 18 is the GPIO pin number
  1. Perhaps the connection is getting cut at some point due to network issues, or issues with the Adafruit_DHT.read_retry taking too long and preventing the client from sending a keepalive packet to the server within the 60 second interval specified. To fix this you could try checking for disconnect using the on_disconnect handler in the mqtt client and reconnecting.
import paho.mqtt.client as mqtt
import time
import sys
import Adafruit_DHT

USERNAME = "username"
PASSWORD = "password"
CLIENT_ID = "client_id"

# The callback for when the client disconnects from the server.
def on_connect(client, cayenne, rc):
    print("Connected with result code "+str(rc))

# The callback for when the client disconnects from the server.
def on_disconnect(client, userdata, rc):
    print("Disconnected with result code "+str(rc))
    reconnected = False
    while not reconnected:
        try:
            client.reconnect()
            reconnected = True
        except:
            print("Reconnect failed, retrying")
            time.sleep(5)

time.sleep(30) #Sleep to allow wireless to connect before starting MQTT
mqttc = mqtt.Client(CLIENT_ID)
mqttc.username_pw_set(USERNAME, password=PASSWORD)
mqttc.on_connect = on_connect
mqttc.on_disconnect = on_disconnect
mqttc.connect("mqtt.mydevices.com", port=1883, keepalive=60)

topic_dht11_temp = "v1/{}/things/{}/data/1".format(USERNAME, CLIENT_ID)
topic_dht11_humidity = "v1/{}/things/{}/data/2".format(USERNAME, CLIENT_ID)
topic_dht22_temp = "v1/{}/things/{}/data/3".format(USERNAME, CLIENT_ID)
topic_dht22_humidity = "v1/{}/things/{}/data/4".format(USERNAME, CLIENT_ID)

while True:
    try:
        mqttc.loop()
        humidity11, temp11 = Adafruit_DHT.read_retry(11, 17) #11 is the sensor type, 17 is the GPIO pin number
        humidity22, temp22 = Adafruit_DHT.read_retry(22, 18) #22 is the sensor type, 18 is the GPIO pin number
        
        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)
        time.sleep(5)
    except (EOFError, SystemExit, KeyboardInterrupt):
        mqttc.disconnect()
        sys.exit()

Alternatively, rather than using paho.mqtt directly you could use the cayenne-mqtt Python module which wraps the paho.mqtt module to make is easier to use. That’s available via pip: cayenne-mqtt · PyPI. Use pip install cayenne-mqtt to install.

An example script using cayenne-mqtt with DHT is below, but it hasn’t been tested with DHT sensors.

#!/usr/bin/env python
import cayenne.client as cayenne
import time
import Adafruit_DHT

# Cayenne authentication info. This should be obtained from the Cayenne Dashboard.
MQTT_USERNAME  = "username"
MQTT_PASSWORD  = "password"
MQTT_CLIENT_ID = "client_id"

client = cayenne.CayenneMQTTClient()
client.begin(MQTT_USERNAME, MQTT_PASSWORD, MQTT_CLIENT_ID)

timestamp = 0

while True:
    client.loop()
    
    if (time.time() > timestamp + 5):
        humidity11, temp11 = Adafruit_DHT.read_retry(11, 17) #11 is the sensor type, 17 is the GPIO pin number
        humidity22, temp22 = Adafruit_DHT.read_retry(22, 18) #22 is the sensor type, 18 is the GPIO pin number

        if temp11 is not None:
            client.virtualWrite(1, temp11, cayenne.TYPE_TEMPERATURE, cayenne.UNIT_CELSIUS)
        if humidity11 is not None:
           client.virtualWrite(2, humidity11, cayenne.TYPE_RELATIVE_HUMIDITY, cayenne.UNIT_PERCENT)
        if temp22 is not None:
            client.virtualWrite(3, temp22, cayenne.TYPE_TEMPERATURE, cayenne.UNIT_CELSIUS)
        if humidity22 is not None:
            client.virtualWrite(4, humidity22, cayenne.TYPE_RELATIVE_HUMIDITY, cayenne.UNIT_PERCENT)
        timestamp = time.time()
3 Likes