def main(): """Primary entry point for the application""" log_format = '[%(asctime)s] %(levelname)s %(message)s' logging.basicConfig(format=log_format, level=logging.INFO) logging.info('** GardenPI Temperature/Humidity Test Utility **') start_time = time.time() dhts = [] # load the config config = utils.load_config() if config['General'].getboolean('UseShelf1'): dhts.append(adafruit_dht.DHT22(int(config['Shelf1'].get('DhtPin', 0)))) if config['General'].getboolean('UseShelf2'): dhts.append(adafruit_dht.DHT22(int(config['Shelf2'].get('DhtPin', 0)))) if config['General'].getboolean('UseShelf3'): dhts.append(adafruit_dht.DHT22(int(config['Shelf3'].get('DhtPin', 0)))) while True: for idx, dht in enumerate(dhts): try: temperature = dht.temperature humidity = dht.humidity print("Device: {}\tTemp: {:.1f} *F\tHumidity: {:.2f}%".format(idx, utils.ctof(temperature), humidity)) except RuntimeError as e: # Reading doesn't always work! Just print error and we'll try again print("Reading from DHT failure: ", e.args) time.sleep(2) logging.info("Script Finished") logging.info("Elapsed Time: %s seconds ", (time.time() - start_time))
def __init__(self): try: self.dht_1 = ad.DHT22(board.D4, False) self.dht_2 = ad.DHT22(board.D27, False) except: self.dht_1.exit() self.dht_2.exit() raise IOError
def __init__(self, app, read_interval, retry_delay=2): self.app = app #GPIO.setmode(GPIO.BCM) # specifiy the DHT device pin = self.app.settings['device_pin'] self.device = adafruit_dht.DHT22(getattr(board, f'D{pin}')) # set the time between reads (ensure its >= 3) self.read_interval = max(3, read_interval) self.interval = 0 self.repeated_readings = self.app.settings['repeated_readings'] agggregation_methods = {'mean': mean, 'median': median} self.aggregation = agggregation_methods[ self.app.settings['reading_aggregation']] # set the time between an unsuccessful read and the next read self.retry_delay = retry_delay # flag that determines which interval is used between reads self.read_successfull = False # set the belay for the main loop self.running_delay = 0.1 # saves the time for calculating the delta time beween iterations self.prev_time = time.time() # storage deque for readings self.storage = deque() # task lists (scheduled actions) self.tasks = [] # count the times a critical error occurred self.error_strikes = 0 self.strike_threshold = 10 # flag to determine if the pi is shutdown at the end self.initialise_shutdown = False
def __init__(self, logger: logging.Logger) -> None: threading.Thread.__init__(self) self.dht_22 = adafruit_dht.DHT22(board.D4) self.running = True self.humidity: Optional[float] = None self.temperature: Optional[float] = None self.logger = logger
def getTH(path_to_record, onoff=True): dhtDevice = adafruit_dht.DHT22(board.D15) if onoff == True: while True: try: # Print the values to the serial port temperature_c = dhtDevice.temperature #temperature_f = temperature_c * (9 / 5) + 32 humidity = dhtDevice.humidity #file = open (path_to_record + "TH.txt" , "a+") print("Time: {} Temp: {:.1f} F / {:.1f} C Humidity: {}% ".format(datetime.datetime.now().strftime("%H:%M:%S"), temperature_c, humidity)) #file.write("Time: {} Temp: {:.1f} F / {:.1f} C Humidity: {}% ".format(datetime.datetime.now().strftime("%H:%M:%S"), temperature_f, temperature_c, humidity)) #file.close() except RuntimeError as error: # Errors happen fairly often, DHT's are hard to read, just keep going print(error.args[0]) time.sleep(5.0) if onoff == False: print("Sensor DHT stopped")
def __init__(self, location): self.location = location self.dhtDevice = adafruit_dht.DHT22(board.D4) self.temps = [] self.humidities = [] self.beginTime = datetime.now() self.endTime = 0
def dht22(): # Initial the dht device, with data pin connected to: dhtDevice = adafruit_dht.DHT22(board.D18) # you can pass DHT22 use_pulseio=False if you wouldn't like to use pulseio. # This may be necessary on a Linux single board computer like the Raspberry Pi, # but it will not work in CircuitPython. # dhtDevice = adafruit_dht.DHT22(board.D18, use_pulseio=False) while True: try: # Print the values to the serial port temperature_c = dhtDevice.temperature temperature_f = temperature_c * (9 / 5) + 32 humidity = dhtDevice.humidity print( "Temp: {:.1f} F / {:.1f} C Humidity: {}% ".format( temperature_f, temperature_c, humidity ) ) except RuntimeError as error: # Errors happen fairly often, DHT's are hard to read, just keep going print(error.args[0]) time.sleep(2.0) continue except Exception as error: dhtDevice.exit() raise error time.sleep(2.0)
def read_data(self): num_reads = 5 readings = [] board_pin = getattr(board, 'D{0}'.format(self.pin)) if self.sensor_type == 22: dht = adafruit_dht.DHT22(board_pin) else: raise Exception("Could not determine sensor type") for x in range(num_reads): try: humidity_reading = dht.humidity temperature_reading = dht.temperature temperature_reading_f = temperature_reading * 1.8 + 32 r = EnvironmentReading(temperature_reading_f, humidity_reading, self.db_id) readings.append(r) time.sleep(1) except: pass temperature = statistics.median( map(lambda rx: rx.temperature, readings)) humidity = statistics.median(map(lambda rx: rx.humidity, readings)) print("{} Median T: {}".format(self.db_id, temperature)) print("{} Median H: {}".format(self.db_id, humidity)) return EnvironmentReading(temperature, humidity, self.db_id)
def initialize_dht_sensor(): global dht_device, dht_sensor_error try: dht_device = adafruit_dht.DHT22(board.D4) except Exception as error: print(error.args[0]) dht_sensor_error = True
def getDataFromSensor(): global HIGH, LOW, UNIT, TEMP, HUM dhtDevice = adafruit_dht.DHT22(board.D4) while True: try: temp = dhtDevice.temperature if UNIT == 'F': temp = temp * (9 / 5) + 32 humidity = dhtDevice.humidity if HIGH == None: HIGH = temp elif HIGH < temp: HIGH = temp if LOW == None: LOW = temp elif temp < LOW: LOW = temp HUM = humidity TEMP = temp log('Temp=' + str(temp) + ', Humidity=' + str(humidity), 'debug') except RuntimeError as error: log(error, level='error') continue time.sleep(2.0)
def __init__(self): self._running = True self.dhtDevice = adafruit_dht.DHT22(board.D4) self.pfad = '/home/pi/Documents/' self.name = self.pfad + datetime.datetime.now().strftime( '%Y-%m-%d_%H-%M') + '.txt' self.my_file = open(self.name, "w+")
def __init__(self, config, i2c): self._name = config.get('Name', '') self._dht = adafruit_dht.DHT22(int(config.get('DhtPin', 0))) self._light_pin = int(config.get('LightPin', 0)) self._water_pin = int(config.get('WaterPin', 0)) if config.getboolean('UseSS'): self._useSS = True self._soil_sensor = Seesaw(i2c, addr=int(config.get('SSAddr', 0x0), 16)) self._soil_min = int(config.get('SSMin', 0)) self._soil_max = int(config.get('SSMax', 0)) else: self._useSS = False self._light_on = False self._water_on = False self._turn_light_on = int(config.get('LightOn', 0)) self._turn_light_off = int(config.get('LightOff', 0)) self._water_on_pct = int(config.get('MoistureOnPct',25)) self._water_off_pct = int(config.get('MoistureOffPct', 75)) self._water_on_time = datetime.strptime(config.get('WaterOnTime', '00:00'), '%H:%M').time() self._water_off_time = datetime.strptime(config.get('WaterOffTime', '00:00'), '%H:%M').time() self._prefix = config.get('Prefix', '') GPIO.setup(self._light_pin, GPIO.OUT, initial=GPIO.HIGH) GPIO.setup(self._water_pin, GPIO.OUT, initial=GPIO.HIGH) self.temperature = 0.0 self.humidity = 0.0 self.soil_temp = 0.0 self.moisture = 0 self.prev_temperature = 0.0 self.prev_humidity = 0.0 self.prev_moisture = 0.0 self.prev_soil_temp = 0 self.water = 0 self.light = 0
class sensorReader: import time import board import busio import adafruit_dps310 import adafruit_dht #initializers i2c = busio.I2C(board.SCL, board.SDA) dps310 = adafruit_dps310.DPS310(i2c) dhtDevice = adafruit_dht.DHT22(board.D4) while True: try: # Print the values to the serial port print("Pressure = %.2f hPa" % dps310.pressure) time.sleep(1) temperature_c = dhtDevice.temperature temperature_f = temperature_c * (9 / 5) + 32 humidity = dhtDevice.humidity print("Temp: {:.1f} F / {:.1f} C \nHumidity: {}% ".format( temperature_f, temperature_c, humidity)) print("") except RuntimeError as error: # Errors happen fairly often, DHT's are hard to read, just keep going print("n/a") print("") time.sleep(60)
def get_measurements(): dht22 = adafruit_dht.DHT22(SENSOR_PIN, use_pulseio=False) temperature = dht22.temperature humidity = dht22.humidity print(f"Humidity= {humidity:.2f}") print(f"Temperature= {temperature:.2f}°C") return temperature, humidity
def read_sensor(n, device): dhtDevice = adafruit_dht.DHT22(device) for i in range(n): try: yield dhtDevice.temperature, dhtDevice.humidity except RuntimeError as error: print(error.args[0]) time.sleep(2.5)
def __init__(self, name, power_pin, data_pin): self._power = digitalio.DigitalInOut(power_pin) self._power.direction = digitalio.Direction.OUTPUT self._on() self._sensor = adafruit_dht.DHT22(data_pin) self.model = "AM2302" super().__init__(name)
def get_temp_and_hum(): '''This is a function that uses DHT22 sensor, It returns two values: - float: Temperature - float: Humidity ''' SENSOR_PIN = D4 dht22 = adafruit_dht.DHT22(SENSOR_PIN, use_pulseio=False) return dht22.temperature, dht22.humidity
def __init__(self, board_pin, sensor_type): if sensor_type == 'DHT11': self.dht = adafruit_dht.DHT11(board_pin) elif sensor_type == 'DHT22': self.dht = adafruit_dht.DHT22(board_pin) else: sys.exit('Invalid DHT sensor code: {}'.format(sensor_type)) self.last_T = 0 self.last_RH = 0
def on_startup(self): try: if USE_LEGACY_DHT: self.sensor = self.sensor_model else: self.sensor = adafruit_dht.DHT22(data_pin, use_pulseio=False) except: self.sensor = None log_exception()
def __init__(self, pin, type='11'): """ :param pin: The pin number (in BCM) of the DHT data line. :type pin: int """ import adafruit_dht if (type == '11'): self.dht = adafruit_dht.DHT11(pin) else: self.dht = adafruit_dht.DHT22(pin)
def __init__(self, sensor: SensorInfo, pin: any, retries: int): self.sensorInfo = sensor self.pin = pin self.retries = retries if sensor.model == MODEL_DHT22: self.dht_device = adafruit_dht.DHT22(pin, use_pulseio=False) elif sensor.model == MODEL_DHT11: self.dht_device = adafruit_dht.DHT11(pin, use_pulseio=False) else: raise
def run_dht22(): dhtDevice = adafruit_dht.DHT22(board.D16) #while True: # Print the values to the serial port temperature_c = dhtDevice.temperature temperature_f = temperature_c * (9 / 5) + 32 humidity = dhtDevice.humidity return temperature_c, humidity
def lab_temp(): #import sys #import Adafruit_DHT dhtDevice = adafruit_dht.DHT22(board.D17) temperature = dhtDevice.temperature humidity = dhtDevice.humidity #humidity, temperature = Adafruit_DHT.read_retry(Adafruit_DHT.AM2302, 17) if humidity is not None and temperature is not None: return render_template("lab_temp.html", temp=temperature, hum=humidity) else: return render_template("no_sensor.html")
def read_sensor(pin, sensor_type, sensor_value): try: if int(sys.argv[1]) == 11: DHT_SENSOR = adafruit_dht.DHT11(pin) if int(sys.argv[1]) == 22: DHT_SENSOR = adafruit_dht.DHT22(pin) if sensor_value == 1: return (DHT_SENSOR.temperature) if sensor_value == 2: return (DHT_SENSOR.humidity) except RuntimeError as error: pass
def __init__(self, id, position, pin): super().__init__(id=id, type="DHT22", position=position, accuracy=0.5) # is accuracy correct? prepared_pin = pin if isinstance(pin, str): prepared_pin = getattr(board, pin) self.backend = adafruit_dht.DHT22(prepared_pin)
def measure_temperature(): # Initialise sensor interface and GCP IOT interface dhtSensor = adafruit_dht.DHT22(board.D4) iot_interface = IOTInterface() while True: temp_c, humidity = get_single_reading(dhtSensor) structured_reading = structure_reading(temp_c, humidity) iot_interface.make_request(structured_reading) time.sleep(SECONDS_BETWEEN_READS)
def __init__(self, sensorGpio, envMemorySize, period): self.envMemory = [] self.envMemoryIndex = -1 self.period = period self.running = False self.thread = threading.Thread(target=self.threadRoutine) self.thread.daemon = True for i in range(envMemorySize): self.envMemory.append([-1, -1, -1]) self.sensorLock = threading.Lock() self.sensor = adafruit_dht.DHT22(sensorGpio)
def __init__(self, name="dome", config={}): # Initialise the dht device, with data pin connected to: import adafruit_dht self.pin = board.D17 self.dhtDevice = adafruit_dht.DHT22(board.D17) self.temperature = -999 self.humidity = -999 self.monitorCadence = config['cadence'] self.name = "dome" self.attachedFan = None self.attachedFans = [] self.fan = False self.exit = False self.logData = {}
def get_DHT_data(): global dht_device try: return {'temperature' : dht_device.temperature, 'humidity' : dht_device.humidity} except: print("get_DHT_data is not connect") while True: try: dht_device.exit() dht_device = DHT.DHT22(dhtPin) print('reconnect getDHTdata') print({'temperature' : dht_device.temperature, 'humidity' : dht_device.humidity}) break except: continue
def get_readings(): attempts = 13 for attempt in range(0, attempts): try: dht_device = adafruit_dht.DHT22(board.D17) humidity = dht_device.humidity DHT22._kill_libgpiod_pulsein() return temperature, humidity except: DHT22._kill_libgpiod_pulsein() time.sleep(1) continue raise ValueError('Unable to get dht22 sensor readings.')