environment sensor library for raspberry dependencies to adafruit exist
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

dht.py 2.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import time
  2. from . import logger, background_task
  3. try:
  4. import adafruit_dht
  5. except ImportError:
  6. logger.warning("Could not import adafruit_dht. DEBUG set to True")
  7. DEBUG = True
  8. else:
  9. from . import DEBUG
  10. class dht_22(background_task):
  11. RUN_SLEEP_TIME = 2.0
  12. MIN_REFRESH_RATE = RUN_SLEEP_TIME
  13. KEY_TEMPERATURE = 'temperature'
  14. KEY_HUMIDITY = 'humidity'
  15. KEY_TIME = 'time'
  16. def __init__(self, gpio, data_callback=None):
  17. self.__data_callback__ = data_callback
  18. # Initial the dht device, with data pin connected to:
  19. if not DEBUG:
  20. self.__dht_device__ = adafruit_dht.DHT22(gpio)
  21. # Initialise background_task
  22. background_task.__init__(self)
  23. def __run__(self):
  24. data = self.__dht_data_transmission__()
  25. if data is not None:
  26. logger.debug('DHT-Communication: Successfully: %s', repr(data))
  27. if self.__data_callback__ is not None:
  28. self.__data_callback__(**data)
  29. def __dht_data_transmission__(self):
  30. if not DEBUG:
  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] = int(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.info('DHT-Communication: ' + error.args[0])
  44. time.sleep(0.1)
  45. except Exception as error:
  46. self.__dht_device__.exit()
  47. raise error
  48. else:
  49. return {
  50. self.KEY_TEMPERATURE: -17.17,
  51. self.KEY_HUMIDITY: 1.7,
  52. self.KEY_TIME: int(time.time()),
  53. }