def probe(dbConnection, tolerant, maxProbeTries): probeTryCount = 0 now = datetime.time(datetime.now()) #Do-While-Schleife für die Validierung try: while True: humidity1, temperature1 = read_retry(sensor=AM2302, pin=2, retries=5) # Try to grab a sensor reading. Use the read_retry method which will retry up humidity2, temperature2 = read_retry(sensor=AM2302, pin=2, retries=5) # to 15 times to get a sensor reading (waiting 2 seconds between each retry). probeTryCount += 1 if None in [humidity1, temperature1, humidity2, temperature2] or probeTryCount >= maxProbeTries or humidity1 < 0 or humidity1 > 100 or temperature1 < 0 or temperature1 > 100: raise ResourceWarning("%s Messung(en) erfolglos. Bitte stellen Sie sicher, dass der Sensor erreichbar ist." % probeTryCount) if abs(temperature1 - temperature2) < 1 and abs(humidity1 - humidity2) < 2: break except ResourceWarning as w: # Falls Messung als gescheitert betrachtet wird, ist eine weitere Berechnung etc. nicht möglich print(w) return 11 # Rückgabewert 11 bedeutet eine Forderung nach Programmabbruch else: humidity = (humidity1+humidity2)/2 temperature = (temperature1+temperature2)/2 #Taupunktberechnung, Formel anhand von TODO: Quelle angeben! aufgebaut und per CAS gekürzt, sodass die Berechnung in einem Schritt erfolgt. dewpt = (-3928.5/(log(humidity*exp(-3928.5/(temperature+231.667)))-4.60517))-231.667 print("%s %0.2f %0.2f %0.2f" % (now, temperature, humidity, dewpt)) with dbConnection: cur = dbConnection.cursor() cur.execute("insert into Probes values ( strftime('%s','now'), ?, ?, ?)", (temperature, humidity, dewpt))
def tick(self, tictime=0): self.hum_1, self.temp_1 = read_retry(AM2302, 14) self.hum_2, self.temp_2 = read_retry(AM2302, 15) self.rolling_temp = self.rolling_temp[-4:] self.rolling_temp.append((self.temp_1 + self.temp_2) / 2.0) self.tictime = time.time()
def main(): Timer(10.0, swapProtocols).start() while True: humidity, temperature = read_retry(SENSOR, PIN) if humidity is not None and temperature is not None: result = '{}\tSensorID=17205700, Temperature={}, Humidity={}'.format(datetime.now(), temperature, round(humidity)) print(result) info(result) print('sending') try: #sock.send(result) #publish.single(MQTT_PATH, result, hostname=MQTT_SERVER) with SWAP_MUTEX: sendMsg(result) except Exception as e: print('failed connection') print(e) info(e) sleep(5) continue print('sent') sleep(5) else: result = 'Failed to get reading. Try again!' info(result)
def get_humidity_am2302(): humidity, temperature = read_retry(dht_sensor, dht_pin) json_string = json.dumps(float('%.3f' % (humidity))) if (json_string == "null"): return [] else: return json_string
def read_sensor(sensor_pin): # Read sensor data humidity, temperature = read_retry(DHT22, sensor_pin) if humidity is None and temperature is None: trace("Failed to get reading on sensor: " + str(sensor_pin), ERROR) return (temperature, humidity)
def read_sensor(): ''' Returns a tuple of 2 floats: humidity in percent e.g. 54.2 stands for 54.2% relative humidity temperature in degrees Celsius. e.g. 32.3 stands for 32.3 degrees Celsius ''' hum, temp = read_retry(DHT22, raspberrypi_data_pin) return hum, temp
def update(self): if self._sensor: self._humidity, temp = read_retry(self._sensor, self.pin) if self.units == 'F': temp = temp * 9 / 5. + 32 self._temperature = temp self.debug('update temp={}, hum={}'.format(temp, self._humidity)) else: self.critical('no sensor')
def get_temperature_humidity(PIN=SETTING_TEMPERATURE_HUMIDITY_SENSOR['PIN']): """Function, return tuple with data: (humidity (%), temperature (C)). """ humidity, temperature = None, None while True: humidity, temperature = read_retry(DHT22, PIN) if humidity is not None and temperature is not None: return measurement(round(humidity, 2), round(temperature, 2))
def read_sensor(self): logging.debug('Reading {} sensor'.format(self.name)) self.hum, self.temp = read_retry(22, self.sensor_chan) if self.hum != None and self.temp != None: logging.debug('{0}: Temp={1:0.1f}* Humidity={2:0.1f}%'.format( self.name, self.temp, self.hum)) return True else: logging.error('Failed to get temperature/humidity ' 'for cage {}'.format(self.name)) return False
def requestData(): # Returns a dictionary with all the data corresponding to a db entry (an Instant) h,t = read_retry(sensor, pin) current_time = time.strftime("%d.%m.%Y.%H.%M").split('.') values = {} values['temp'], values['hum'] = get_temp_and_hum() values['day'] = current_time[0] values['month'] = current_time[1] values['year'] = current_time[2] values['hour'] = current_time[3] values['minute'] = current_time[4] return values
def poll_sensor(self): """Poll the sensor to get the temp and humidity""" # Try to grab a sensor reading. Use the read_retry method which will retry up to 15 times # to get a sensor reading (waiting 2 seconds between each retry). humidity, temperature = read_retry(self.sensor, self.pin) # Note that sometimes you won't get a reading and the results will be null (because Linux # can't guarantee the timing of calls to read the sensor). If this happens try again! if humidity is not None and temperature is not None: temphumid = (humidity, temperature) return temphumid else: raise EnvironmentError( 'Failed to get a reading from DHT22') # pragma: no cover
def _detect(self, celsius, fahrenheit, poll_time): """ Thread for detecting temperature. Uses Adafruit_DHT module to detect temperature of environment. Properties ---------- Inherits **kwargs from detect method. """ while True: self.humidity, self.temperature = read_retry( self.sensor, self.pin) if celsius: pass else: self.temperature = self.temperature * 9 / 5.0 + 32 sleep(poll_time)
def run(self): self.is_running = True while self.is_running: sleep(EnvironmentalSensor.MAX_READ_INTERVAL) relative_humidity, temperature = read_retry(DHT22, self.sensor_pin) if relative_humidity is not None or temperature is not None: entry = LogEntry( self.hardware_device_id, relative_humidity, temperature) EnvironmentalSensor.logger.info(entry) self.latest_log_entry.set_value(entry) if self.entry_queue is not None: EnvironmentalSensor.logger.debug('Enqueued Log Entry') self.entry_queue.put(entry) else: EnvironmentalSensor.logger.warning('Failed to read from sensor')
SENSOR_COUNT = len(SENSOR_PINS) GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(SWITCH_PIN, GPIO.OUT) switch_on = False sleep_time = SAMPLE_INTERVAL db = MongoClient().local while True: data = {"dt": datetime.now().strftime('%Y-%m-%d %H:%M:%S')} avg_humid = 0 for pin in SENSOR_PINS: humid, temp = read_retry(DHT22, pin) avg_humid += humid data[str(pin)] = {"h": round(humid, 3), "t": round(temp, 3)} avg_humid /= SENSOR_COUNT if switch_on: if avg_humid > HUMID_UPPER: GPIO.output(SWITCH_PIN, GPIO.LOW) sleep_time = SAMPLE_INTERVAL data['on'] = 0 switch_on = False else: if avg_humid < HUMID_LOWER: GPIO.output(SWITCH_PIN, GPIO.HIGH) sleep_time = MEASURE_INTERVAL
def getDHT11Data(): """return humidity and temperature from DHT11""" humidity, temperature = read_retry(11, 4) return humidity, temperature
def get_am2302_string(): humidity, temperature = read_retry(dht_sensor, dht_pin) data = "T: %.1fC H: %.0f%%" % (temperature, humidity) return data
def update(self): self._humidity, temp = read_retry(self._sensor, self.pin) if self.units == 'F': temp = temp * 9 / 5. + 32 self._temperature = temp
if __name__ == '__main__': blanks = " " * 16 lcd.clear() lcd.cursor_pos = (0, 0) lcd.write_string('CO2: ') lcd.cursor_pos = (1, 0) lcd.write_string('T: ') beginning_time = time.time() with open('record.csv', 'w') as f: fw = csv.writer(f) fw.writerow(('time', 'CO2-PPM', 'Temp-C', 'Humidity-PCT')) while True: thetime = time.time() co2 = read_CO2()['CO2'] humidity, temperature = read_retry(11, 17) lcd.cursor_pos = (0, 5) lcd.write_string((str(co2) + ' PPM' + blanks)[:16 - 5]) lcd.cursor_pos = (1, 3) t_string = '%d' % temperature + 'C' h_string = '%d' % humidity + '%' lcd.write_string((t_string + ' H:' + h_string + blanks)[:16 - 6]) print('CO2:', co2, 'T:', temperature, 'H:', humidity) fw.writerow((thetime, co2, temperature, humidity)) time.sleep(1)
def get_temp_and_hum(): h,t = read_retry(sensor, pin) return round(t,1) ,round(h,1)
'value': heat2, timestamp: timestamp }, { 'variable': uptime.id, 'value': 1, timestamp: timestamp }]) except: print("Error saving data to ubidots") traceback.print_exc() print("Beginning main event loop") while (True): try: hum_1, temp_1 = read_retry(AM2302, 14) hum_2, temp_2 = read_retry(AM2302, 15) last_avg_temp = (temp_1 + temp_2) / 2 if HEATER_IS_ON and (last_avg_temp > 30.2): toggle_heater_state() if not HEATER_IS_ON and (last_avg_temp < 29.8): toggle_heater_state() hs = 1 if HEATER_IS_ON else 0 write_sensor_data(temp_1, temp_2, hum_1, hum_2, hs, hs) time.sleep(5) except: print("Program exiting! Turning heater off...")
# create db client db = InfluxDBClient(host=end, database=dbname) try: # if there is no db running on endpoint this will error db.get_list_database() except KeyboardInterrupt: exit except Exception as e: db = None sleep(60) log("database found sending data") while db is not None: h, t = None, None if s is not None: h, t = read_retry(s, p) # if the h, t objects exists if h is not None and t is not None: # create a message containing telemetry msg1 = [{ 'measurement': 'atmos', 'tags': { "host": gethostname() }, 'fields': { 'cpu_usage': float("%.2f" % cpu_percent()), 'mem_usage': float("%.2f" % virtual_memory().percent), 'cpu_temp': temp(), 'temp': float("%.2f" % t), 'humi': float("%.2f" % h)
def get_humidity_temperature(self): from Adafruit_DHT import read_retry, DHT11 hum, temp = read_retry(DHT11, self.sensor_pin) hum = int(hum) temp = int(temp) return hum, temp
def main(): while True: humidity, temp = read_retry(DHT11, 18) if humidity is not None: print("Current Humidity={}% and temp={}".format(humidity, temp)) sleep(2)
def raw_dht(): sensor = DHT11 pin = 21 return read_retry(sensor, pin)
def getData(self): data = [self.getName(), 0, 0] data[1], data[2] = read_retry(DHT11, self.__pin, 7, 0.01) return data
def raw_dht(): return read_retry(sensor, pin)
def get_temp_humidity(): humidity, temp = read_retry(DHT22, 4) temp = (temp * 9/5) + 32 return temp, humidity
def get_hum_and_temp(): h, t = read_retry(sensor, pin) return round(h, 1), round(t, 1)