56 lines
2.0 KiB
Python
56 lines
2.0 KiB
Python
|
import adafruit_dht
|
||
|
import threading
|
||
|
import time
|
||
|
|
||
|
from . import logger
|
||
|
|
||
|
|
||
|
class dht_22(object):
|
||
|
KEY_TEMPERATURE = 'temperature'
|
||
|
KEY_HUMIDITY = 'humidity'
|
||
|
KEY_TIME = 'time'
|
||
|
|
||
|
def __init__(self, gpio, data_callback=None):
|
||
|
self.__data_callback__ = data_callback
|
||
|
# Initial the dht device, with data pin connected to:
|
||
|
self.__dht_device__ = adafruit_dht.DHT22(gpio)
|
||
|
self.__active__ = True
|
||
|
self.__thread__ = threading.Thread(target=self.run, args=())
|
||
|
self.__thread__.daemon = True # Daemonize thread
|
||
|
self.__thread__.start() # Start the execution
|
||
|
|
||
|
def run(self):
|
||
|
while self.__active__:
|
||
|
data = self.__dht_data_transmission__()
|
||
|
if data is not None:
|
||
|
logger.debug('DHT-Communication: Successfully: %s', repr(data))
|
||
|
if self.__data_callback__ is not None:
|
||
|
self.__data_callback__(**data)
|
||
|
time.sleep(2.0)
|
||
|
|
||
|
def close(self):
|
||
|
self.__active__ = False
|
||
|
self.__thread__.join()
|
||
|
|
||
|
def __del__(self):
|
||
|
self.close()
|
||
|
|
||
|
def __dht_data_transmission__(self):
|
||
|
while self.__active__:
|
||
|
try:
|
||
|
# Store the values
|
||
|
data = {}
|
||
|
data[self.KEY_TEMPERATURE] = self.__dht_device__.temperature
|
||
|
data[self.KEY_HUMIDITY] = self.__dht_device__.humidity
|
||
|
data[self.KEY_TIME] = time.time()
|
||
|
if data[self.KEY_TEMPERATURE] is not None and data[self.KEY_HUMIDITY] is not None:
|
||
|
return data
|
||
|
time.sleep(2.0)
|
||
|
except RuntimeError as error:
|
||
|
# Errors happen fairly often, DHT's are hard to read, just keep going
|
||
|
logger.debug('DHT-Communication: ' + error.args[0])
|
||
|
time.sleep(0.1)
|
||
|
except Exception as error:
|
||
|
self.__dht_device__.exit()
|
||
|
raise error
|