Guest User

Untitled

a guest
Jan 15th, 2019
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.42 KB | None | 0 0
  1. #!/usr/bin/python3
  2. import os
  3. import time
  4. import sys
  5. import Adafruit_DHT as dht
  6. import paho.mqtt.client as mqtt
  7. import json
  8. import datetime
  9. #
  10. # Sensor should be set to Adafruit_DHT.DHT11, Adafruit_DHT.DHT22, or Adafruit_DHT.AM2302.
  11. sensor = dht.DHT11
  12. pin = 4
  13.  
  14. BROKER = 'localhost'
  15.  
  16. # Data capture and upload interval in seconds.
  17. INTERVAL=15
  18.  
  19. sensor_data = {'date': 0, 'temperature': 0, 'humidity': 0}
  20.  
  21. next_reading = time.time()
  22.  
  23. client = mqtt.Client()
  24.  
  25. # Connect to BROKER using default MQTT port and 60 seconds keepalive interval
  26. client.connect(BROKER, 1883, 60)
  27.  
  28. client.loop_start()
  29.  
  30. try:
  31. while True:
  32. humidity,temperature = dht.read_retry(sensor, pin)
  33. humidity = round(humidity, 2)
  34. temperature = round(temperature, 2)
  35. print(u"Temperature: {:g}u00b0C, Humidity: {:g}%".format(temperature, humidity))
  36. sensor_data['temperature'] = temperature
  37. sensor_data['humidity'] = humidity
  38. sensor_data['date'] = datetime.datetime.now().replace(microsecond=0).isoformat()
  39.  
  40. # client.publish('test_channel', json.dumps(sensor_data), 1)
  41. client.publish('test_channel', json.dumps(sensor_data), 2)
  42.  
  43. next_reading += INTERVAL
  44. sleep_time = next_reading-time.time()
  45. if sleep_time > 0:
  46. time.sleep(sleep_time)
  47. except KeyboardInterrupt:
  48. pass
  49.  
  50. client.loop_stop()
  51. client.disconnect()
  52.  
  53. 1547597521: Saving in-memory database to /var/lib/mosquitto/mosquitto.db.
Add Comment
Please, Sign In to add comment