Advertisement
gregwa

FCM 133 - MQTT/DHT22 Raspberry Pi

May 4th, 2018
360
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.34 KB | None | 0 0
  1. #!/usr/bin/python
  2. #  -*- coding: utf-8 -*-
  3. # ================================================================
  4. # simpletest.py
  5. # ----------------------------------------------------------------
  6. # Code modified from Adafruit sample code simpletest.py from the
  7. # DHT library
  8. # ----------------------------------------------------------------
  9. # Modifications by G.D. Walters for Full Circle Magazine #132
  10. # ================================================================
  11.  
  12. import Adafruit_DHT
  13. # import the paho library
  14. # also import the time library for the sleep function
  15. import paho.mqtt.client as mqtt
  16. from time import sleep
  17.  
  18. # Set some global definitions
  19. MQTT_SERVER = '192.168.1.224'
  20. MQTT_PATH1 = 'greghouse/dht22/humidity'
  21. MQTT_PATH2 = 'greghouse/dht22/temperature'
  22.  
  23. sensor = Adafruit_DHT.DHT22
  24.  
  25. pin = 4   # GPIO Input pin for data from the sensor Physical pin 7
  26. sleep(3)  # Wait 3 seconds before starting up for things to stabilize…
  27.  
  28. def on_connect(client,userdata,flags, rc):
  29.     print('Connected with result code ' + str(rc))
  30.     client.subscribe(MQTT_PATH1)
  31.     client.subscribe(MQTT_PATH2)
  32.    
  33.  
  34. # The callback for when a PUBLISH message is received from the broker.
  35. def on_message(client, userdata, msg):
  36.     print(msg.topic+' '+str(msg.payload))
  37.     # more callbacks, etc.
  38.  
  39.  
  40. client = mqtt.Client()
  41. client.on_connect = on_connect
  42. client.on_message = on_message
  43.  
  44. client.connect(MQTT_SERVER, 1883, 60)
  45.  
  46. while 1:
  47.     humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
  48.     # Temp in centigrade
  49.     temperaturec = temperature
  50.     # Temp in fahrenheit
  51.     temperaturef = temperature * 9/5.0 + 32
  52.  
  53.     if humidity is not None and temperature is not None:
  54.         # If using Celsius, change the '*F' to '*C'
  55.         # and use temperaturec
  56.         print('Temp={0:0.1f}*F  Humidity={1:0.1f}%'.format(
  57.                                                            temperaturef,
  58.                                                            humidity))
  59.         hmsg = '{0:0.1f}'.format(humidity)
  60.         # Change the next line to temperaturec if you want to
  61.         # publish in centigrade
  62.         tmsg = '{0:0.1f}'.format(temperaturef)
  63.         client.publish(MQTT_PATH1,hmsg,qos=1,retain=True)
  64.         client.publish(MQTT_PATH2,tmsg,qos=1,retain=True)
  65.     else:
  66.         print('Failed to get reading. Try again!')
  67.  
  68.     sleep(5)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement