async def _show_weather_bme280(self): data = bme280.sample(bus, address, calibration_params) await send_text_to_room( self.client, self.room.room_id, f"Current temperature {round(Decimal(data.temperature))} C, pressure {round(Decimal(data.pressure))}HPa and humidity {round(Decimal(data.humidity))}%", )
def getBME(): bme280_data = bme280.sample(I2C_BUS, I2C_BME_ADDRESS) return { "humidity": bme280_data.humidity, "pressure": bme280_data.pressure, "ambient_temperature": bme280_data.temperature }
def updateSensorValues(): sensorsResponse = [] # '1-wire' sensor reading sensorId = "28-01193a653db9" tempfile = open("/sys/bus/w1/devices/{0}/w1_slave".format(sensorId)) temptext = tempfile.read() tempfile.close() tempcelsius = temptext.split("\n")[1].split(" ")[9] temperature = float(tempcelsius[2:]) temperature = temperature / 1000 sensorsResponse.append({"name": "waterTemp", "value": temperature}) # BME280 sensor reading port = 1 address = 0x76 bus = smbus2.SMBus(port) calibration_params = bme280.load_calibration_params(bus, address) data = bme280.sample(bus, address, calibration_params) sensorsResponse.append({"name": "roomTemp", "value": data.temperature}) sensorsResponse.append({"name": "pressure", "value": data.pressure}) sensorsResponse.append({"name": "roomHumidity", "value": data.humidity}) # values return return json.dumps(sensorsResponse)
def load_raw_data(self): sensor_data = None try: sensor_data = self.get_empty_data_set() (address,bus) = self.__get_address() with smbus2.SMBus(bus) as i2cbus: calibration_params = bme280.load_calibration_params(i2cbus, address) # the sample method will take a single reading and return a # compensated_reading object data = bme280.sample(i2cbus, address, calibration_params) # the compensated_reading class has the following attributes sensor_data['temperature'] = data.temperature sensor_data['humidity'] = data.humidity sensor_data['pressure'] = data.pressure # https://github.com/avislab/sensorstest/blob/master/BME280/BME280.py#L176 sensor_data['altitude'] = sensor_data['pressure']/101325.0 sensor_data['altitude'] = 1 - pow(sensor_data['altitude'], 0.19029) sensor_data['altitude'] = round(44330.0*sensor_data['altitude'], 3) except Exception as ex: print('terrariumBME280Sensor Ex:') print(ex) return sensor_data
def main(): # this will take a single reading and return a # compensated_reading object data = bme280.sample(bus, address, calibration_params) r = requests.post(API_ENDPOINT, data={'celsius': data.temperature}) print(r.text)
def get_sample(self): sample = bme280.sample(self.bus, self.address) machine = Machine(sample.temperature, sample.pressure) ambient = Ambient(sample.temperature, sample.humidity) return MessageBody(machine, ambient, str(sample.timestamp), sample.id)
def __init__(self): self.data_dict = {} self.port = 1 self.address = 0x76 self.bus = smbus2.SMBus(self.port) bme280.load_calibration_params(self.bus, self.address) self.bme280_data = bme280.sample(self.bus, self.address)
def read_data_new(self) -> Dict: """ read data from BME280 sensor in a robust way""" val = {} count = 5 while 0 < count: try: with smbus2.SMBus(self.port) as bus: calibration_params = bme280.load_calibration_params( bus, self.address) data = bme280.sample(bus, self.address) val = { "temperature": "{:.1f}".format(data.temperature), "humidity": "{:.1f}".format(data.humidity), "pressure": "{:.1f}".format(data.pressure) } except OSError as error: self.logger.info("OSError: %s", error) if val: break count -= 1 self.logger.error("Could not read new value, try %s more time(s)", count) return val
def get_bme280_measurements(): data = bme280.sample(bus, BME_ADDRESS, calibration_params) response_model = {} response_model["temperature"] = data.temperature response_model["humidity"] = data.humidity response_model["pressure"] = data.pressure return json.dumps(response_model)
def readBME(self): try: data = bme280.sample(self.bme["bus"],self.bme["address"],self.bme["cp"]) return data except Exception as e: print("error while getting bme",str(e)) return AttrDict({"temperature":None,"humidity": None, "pressure": None})
def get_bme280_data(**kwargs): verbose = kwargs['verbose'] read_interval = kwargs['BME280_read_interval'] try: import smbus2 import bme280 from time import sleep port = 1 address = kwargs['BME280_i2c_address'] bus = smbus2.SMBus(port) redis_db = db_connect('localhost', 0) while True: calibration_params = bme280.load_calibration_params(bus, address) data = bme280.sample(bus, address, calibration_params) redis_db.mset({ 'BME280_Humidity': data.humidity, 'BME280_Temperature': data.temperature, 'BME280_Pressure': data.pressure }) redis_db.expire('BME280_Temperature', read_interval * 2) redis_db.expire('BME280_Humidity', read_interval * 2) redis_db.expire('BME280_Pressure', read_interval * 2) if bool(verbose) is True: print('') print('BME280 Humidity: {0:0.0f}%'.format(data.humidity)) print('BME280 Temperature: {0:0.1f}\xb0C'.format( data.temperature)) print('BME280 Pressure: {0:0.0f}hPa'.format(data.pressure)) print('') sleep(read_interval) except Exception as err: print(f'Problem with {err}')
def root(): data = bme280.sample(bus, address, calibration_params) temp = str(round(data.temperature, 2)) pressure = str(round(data.pressure, 2)) humidity = str(round(data.humidity, 2)) result = ("Temperature: " + temp + ", Pressure: " + pressure + ", Humidity: " + humidity) return result
def sensor_read(): bme280_data = bme280.sample(bus, address) sensor_read.humidity = int(bme280_data.humidity) sensor_read.pressure = round(bme280_data.pressure) / 10 sensor_read.temperature = round(bme280_data.temperature, 2) print(sensor_read.humidity, sensor_read.pressure, sensor_read.temperature) sleep(1)
def main(): port = 1 address = 0x76 bus = smbus2.SMBus(port) # compensation_params = bme280.load_calibration_params(bus, address) # the sample method will take a single reading and return a # compensated_reading object data = bme280.sample(bus, address) # print("compensation_params = {0}".format(compensation_params)) # the compensated_reading class has the following attributes: # # data.id # data.timestamp # data.temperature # data.pressure # data.humidity # data.uncompensated # print(data.uncompensated) # # there is a handy string representation too # print(data) return { "timestamp": data.timestamp.timestamp(), "temperature": data.temperature, "pressure": data.pressure, "humidity": data.humidity, }
def sensarHumedad(): ''' Función que obtiene la presión del sensor bme280 y la almacena en la base de datos junto con el tiempo de medición ''' # Obtener todos los datos del sensor datos = bme280.sample(bus, direccion, parametros_calibracion) # Obtener humedad humedad = datos.humidity # Redondear humedad a 3 decimales humedad = round(humedad, 3) # Imprimir resultado print("Humedad: " + str(humedad) + " % rH") # Agregar dato a la base de datos # Abrir el cursor para escribir en la BD cur = conn.cursor() # Obtener tiempo actual tiempo = int(time.time()) # Crear comando SQL comando = "insert into humedades values (" + str(tiempo) + ", " + str( humedad) + ")" # Ejecutar el comando cur.execute(comando) # Guardar los cambios conn.commit() # Cerrar el cursor cur.close()
def readData(): data = bme280.sample(bus, i2c_address, calibration_params) datas = {'temperature':data.temperature ,\ 'pressure':data.pressure, 'humidity':data.humidity} return datas
def read_sensors(): global dev, bus, address, calibration_params, temp, pre, hum, pm10, pm2_5, color10, color2_5 # Read BME280 data = bme280.sample(bus, address, calibration_params) temp = round(data.temperature, 1) pre = int(data.pressure) hum = int(data.humidity) # Read PM dev.flushInput() msg = dev.read(10) assert msg[0] == ord(b'\xaa') assert msg[1] == ord(b'\xc0') assert msg[9] == ord(b'\xab') checksum = sum(v for v in msg[2:8]) % 256 assert checksum == msg[8] pm2_5 = (msg[3] * 256 + msg[2]) / 10 pm10 = (msg[5] * 256 + msg[4]) / 10 color10 = 'yellow' color2_5 = 'yellow' if pm10 > 40: color10 = 'red' if pm2_5 > 30: color2_5 = 'red'
def test_sample_with_params(): compensation_params = bme280.params() compensation_params.dig_H1 = 0 compensation_params.dig_H2 = 1 compensation_params.dig_H3 = 4 compensation_params.dig_H4 = 3 compensation_params.dig_H5 = 5 compensation_params.dig_H6 = 6 compensation_params.dig_P1 = 10 compensation_params.dig_P2 = 11 compensation_params.dig_P3 = 12 compensation_params.dig_P4 = 13 compensation_params.dig_P5 = 14 compensation_params.dig_P6 = 15 compensation_params.dig_P7 = 16 compensation_params.dig_P8 = 17 compensation_params.dig_P9 = 18 compensation_params.dig_T1 = 20 compensation_params.dig_T2 = 21 compensation_params.dig_T3 = 22 smbus.write_byte_data = MagicMock() smbus.read_i2c_block_data = MagicMock(return_value=list(range(8))) data = bme280.sample(bus=smbus, address=0x76, compensation_params=compensation_params) assert data.pressure == 8801790.518824806 assert data.temperature == 0.0030482932925224304 assert data.humidity == 0.02082886288568924
def meter(): while True: #Calculate CPU temperature of Raspberry Pi in Degrees C temp1 = int(open('/sys/class/thermal/thermal_zone0/temp').read()) / 1e3 # Get Raspberry Pi CPU temp humi, temp = dht.read_retry(dht.DHT22, 23) vis=Sensor.Si1145_readVisible() IR=Sensor.Si1145_readIR() UVindex=Sensor.Si1145_readUV() temp = '%.2f' % temp humi = '%.2f' % humi bme280_data=bme280.sample(bus,address) secondarytemp=bme280_data.temperature pressure=bme280_data.pressure params = urllib.urlencode({'field1': temp, 'field2': humi ,'field3': temp1 ,'field4': pressure, 'field5': IR,'field6': vis,'field7': UVindex, 'key':key }) headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain"} conn = httplib.HTTPConnection("api.thingspeak.com:80") try: conn.request("POST", "/update", params, headers) response = conn.getresponse() print temp, humi, temp1, pressure, IR, vis, UVindex print response.status, response.reason data = response.read() conn.close() except: print "connection failed" break
def readSensor(): port = 1 address = 0x77 bus = smbus2.SMBus(port) task = request.args.get("task") calibration_params = bme280.load_calibration_params(bus, address) # the sample method will take a single reading and return a # compensated_reading object data = bme280.sample(bus, address, calibration_params) # the compensated_reading class has the following attributes print(data.id) print(data.timestamp) print(data.temperature) print(data.pressure) print(data.humidity) response = [{ "timestamp": data.timestamp, "temperature": data.temperature, "humidity": data.humidity, "pressure": data.pressure, }] # response.append({"timestamp": data.timestamp}) # if(task == "getTemperature"): # response.append({"sensor_val":data.temperature}) # return jsonify(response) # elif(task == "getPressure"): # response.append({"sensor_val": data.pressure}) # return jsonify(response) # else: # response.append({"sensor_val": data.humidity}) return jsonify(response)
def request_data(): port = 1 address = 0x76 bus = smbus2.SMBus(port) calibration_params = bme280.load_calibration_params(bus, address) data = bme280.sample(bus, address, calibration_params) return data
def report(): data = bme280.sample(bus, address, calibration_params) API_URL = 'http://grisham.shelms.io/api/' T = requests.post(API_URL + 'T', data={'celesius': data.temperature}) H = requests.post(API_URL + 'H', data={'RH': data.humidity}) P = requests.post(API_URL + 'P', data={'BP': data.pressure}) print(T.text + H.text + P.text)
def main(): StartMQTT() while True: MessageLoop(bot, handle).run_as_thread() #ThingWorx() GPIO.output(4,GPIO.HIGH) calibration_params = bme280.load_calibration_params(bus, address) data = bme280.sample(bus, address, calibration_params) temp1 = data.temperature pay_load = "Temp =" + str(temp1) my_mqtt = mqtt.Client() my_mqtt.connect(mqtt_broker,port=1883) print("--connected to broker") try: my_mqtt.publish(topic, pay_load) print("--Temp = %.1f" % temp1) except: print("--error") else: print("--disconnected") time.sleep(2)
def readData(): data = bme280.sample(_BUS, _I2C_ADDRESS, _CALIBRATION_PARAMS) datas = {'temperature':data.temperature , 'pressure':data.pressure, 'humidity':data.humidity} return datas
def bme_sample(bus, address, calibration): try: data = bme280.sample(bus, address, calibration) return round(data.temperature, 2), round(data.humidity, 2), round(data.pressure, 2) except: return -99, -99, -99
def main(): interval = 15 while True: ts = int(time.time()) data = bme280.sample(bus, address, calibration_params) if data: temp_c = data.temperature temp_f = 9.0 / 5.0 * temp_c + 32 print "bme280.temp_c %s %.2f" % (ts, temp_c) print "bme280.temp_f %s %.2f" % (ts, temp_f) print "bme280.pressure_hpa %s %.2f" % (ts, data.pressure) print "bme280.pressure_inch %s %.2f" % (ts, data.pressure / 33.87) humidity = data.humidity if humidity <= 100: print "bme280.humid %s %.2f" % (ts, humidity) else: sleep(2) next sys.stdout.flush() time.sleep(interval)
def main(): data = bme280.sample(bus, address, calibration_params) freesans = ImageFont.truetype( '/usr/share/fonts/truetype/lato/Lato-Black.ttf', 20) freesans15 = ImageFont.truetype( '/usr/share/fonts/truetype/lato/Lato-Black.ttf', 15) freesans12 = ImageFont.truetype( '/usr/share/fonts/truetype/lato/Lato-Black.ttf', 12) freesans10 = ImageFont.truetype( '/usr/share/fonts/truetype/lato/Lato-Black.ttf', 10) Piboto15 = ImageFont.truetype("Piboto-Regular.ttf", 15) with canvas(device) as draw: #draw.rectangle(device.bounding_box, outline="white", fill="black") draw.text((5, 10), "%3.2f\u00b0F" % (data.temperature * 9 / 5 + 32), font=freesans15, fill="white") draw.text((0, 0), "Room Temp:", font=freesans12, fill="white") draw.text((1, 37), str(data.timestamp), font=freesans15, fill="white") draw.text((25, 23), "Time-Date:", font=freesans15, fill="white") draw.text((75, 0), "Humidity:", font=freesans12, fill="white") draw.text((75, 10), "%3.2f" % (data.humidity), font=freesans15, fill="white") draw.text((115, 10), "%", font=freesans15, fill="white") #draw.text((46,10), "F", font=freesans15, fill="white") draw.text((8, 52), (lan_ip()), font=freesans10, fill="white") print(data.temperature * 9 / 5 + 32)
def sensarTemperatura(): ''' Función que obtiene la temperaturra del sensor bme280 y la almacena en la base de datos junto con el tiempo de medición ''' # Obtener todos los datos del sensor datos = bme280.sample(bus, direccion, parametros_calibracion) # Obtener temperatura temperatura = datos.temperature # Redondear temperatura a 3 decimales temperatura = round(temperatura, 3) # Imprimir resultado print("Temperatura: " + str(temperatura) + " ºC") # Agregar dato a la base de datos # Abrir el cursor para escribir en la BD cur = conn.cursor() # Obtener tiempo actual tiempo = int(time.time()) # Crear comando SQL comando = "insert into temperaturas values (" + str(tiempo) + ", " + str( temperatura) + ")" # Ejecutar el comando cur.execute(comando) # Guardar los cambios conn.commit() # Cerrar el cursor cur.close()
def __init__(self): self.data_dict = {} port = 1 address = 0x76 bus = smbus2.SMBus(port) bme280.load_calibration_params(bus, address) self.bme280_data = bme280.sample(bus, address)
def run(self): if True: try: new_env_data = IndoorEnvironmentData() bme280_data = bme280.sample(self.bus, self.ADDRESS) new_env_data.humidity = bme280_data.humidity new_env_data.pressure = bme280_data.pressure new_env_data.temperature = bme280_data.temperature self.collection.indoor_environment_data = new_env_data except Exception as e: self.logger.error('Failed to fetch indoor environment: %s', str(e)) raise Exception('Failed to fetch indoor environment') try: self.collection.ambient_light = self.apds.readAmbientLight() if False: # if apds.isGestureAvailable(): print(f"gesture available") motion = self.apds.readGesture() print(f"gesture code {motion}") if (motion == APDS9960_DIR_UP): new_env_data.time_offset += 15 elif (motion == APDS9960_DIR_DOWN): new_env_data.time_offset -= 15 except Exception as e: self.logger.error('Failed to fetch brightness: %s', str(e)) raise Exception('Failed to fetch brightness')