environment sensor library for raspberry dependencies to adafruit exist
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import adafruit_dht
  2. import threading
  3. import time
  4. from . import logger
  5. class dht_22(object):
  6. KEY_TEMPERATURE = 'temperature'
  7. KEY_HUMIDITY = 'humidity'
  8. KEY_TIME = 'time'
  9. def __init__(self, gpio, data_callback=None):
  10. self.__data_callback__ = data_callback
  11. # Initial the dht device, with data pin connected to:
  12. self.__dht_device__ = adafruit_dht.DHT22(gpio)
  13. self.__active__ = True
  14. self.__thread__ = threading.Thread(target=self.run, args=())
  15. self.__thread__.daemon = True # Daemonize thread
  16. self.__thread__.start() # Start the execution
  17. def run(self):
  18. while self.__active__:
  19. data = self.__dht_data_transmission__()
  20. if data is not None:
  21. logger.debug('DHT-Communication: Successfully: %s', repr(data))
  22. if self.__data_callback__ is not None:
  23. self.__data_callback__(**data)
  24. time.sleep(2.0)
  25. def close(self):
  26. self.__active__ = False
  27. self.__thread__.join()
  28. def __del__(self):
  29. self.close()
  30. def __dht_data_transmission__(self):
  31. while self.__active__:
  32. try:
  33. # Store the values
  34. data = {}
  35. data[self.KEY_TEMPERATURE] = self.__dht_device__.temperature
  36. data[self.KEY_HUMIDITY] = self.__dht_device__.humidity
  37. data[self.KEY_TIME] = time.time()
  38. if data[self.KEY_TEMPERATURE] is not None and data[self.KEY_HUMIDITY] is not None:
  39. return data
  40. time.sleep(2.0)
  41. except RuntimeError as error:
  42. # Errors happen fairly often, DHT's are hard to read, just keep going
  43. logger.debug('DHT-Communication: ' + error.args[0])
  44. time.sleep(0.1)
  45. except Exception as error:
  46. self.__dht_device__.exit()
  47. raise error