Ejemplo n.º 1
0
    def poll(cls, sensor: Sensor) -> "BME280":
        sensor.update_sensor()

        return BME280(
            humidity=sensor.humidity,
            pressure=sensor.pressure,
            temperature=sensor.temperature,
        )
def presMessage():
    bme280: BME280 = BME280()
    ltr559: LTR559 = LTR559()

    cpu_temps = [get_cpu_temperature()] * 5


    while(1):	
        time.sleep(1)
        amps = noise.get_amplitudes_at_frequency_ranges([(20,20000)])

        cpu_temp = get_cpu_temperature()
        # Smooth out with some averaging to decrease jitter
        cpu_temps = cpu_temps[1:] + [cpu_temp]
        avg_cpu_temp = sum(cpu_temps) / float(len(cpu_temps))
        raw_temp = bme280.get_temperature()
        comp_temp = raw_temp - ((avg_cpu_temp - raw_temp) / factor)


        sio.emit('psiresponse', bme280.get_pressure())
        sio.emit('tempresponse', comp_temp)
        sio.emit('humresponse', bme280.get_humidity())
        sio.emit('lightresponse', ltr559.get_lux())
        sio.emit('noiseresponse', amps[0])
        co = gas.read_all()
        co = co/1000
        sio.emit('gasresponse', gas.read_all())
Ejemplo n.º 3
0
def main():
    signal.signal(signal.SIGTERM, handler)
    signal.signal(signal.SIGINT, handler)

    bus = SMBus(1)
    bme280 = BME280(i2c_dev=bus)

    sakuraio = SakuraIOSMBus()

    try:
        while (sakuraio.get_connection_status() and 0x80) == 0:
            time.sleep(1)

        print("Connected")

        while True:
            temperature = bme280.get_temperature()
            pressure = bme280.get_pressure()
            humidity = bme280.get_humidity()
            measures = 'A{}?t|{:05.2f}|h|{:05.2f}|p|{:05.2f}A'.format(
                key, temperature, humidity, pressure)
            print(measures)
            for i in range(math.ceil(len(measures) / 8)):
                sakuraio.enqueue_tx(i, measures[i * 8:i * 8 + 8])
            sakuraio.send()
            print("Send Data")
            time.sleep(wait)

    except Exception as e:
        print(e)
Ejemplo n.º 4
0
def main():
    signal.signal(signal.SIGTERM, handler)
    signal.signal(signal.SIGINT, handler)

    bus = SMBus(1)
    bme280 = BME280(i2c_dev=bus)

    sakuraio = SakuraIOSMBus()

    try:
        while (sakuraio.get_connection_status() and 0x80) == 0:
            time.sleep(1)

        print("Connected")

        while True:
            sakuraio.enqueue_tx(
                0, float('{:05.2f}'.format(bme280.get_temperature())))
            sakuraio.enqueue_tx(
                1, float('{:05.2f}'.format(bme280.get_humidity())))
            sakuraio.enqueue_tx(
                2, float('{:05.2f}'.format(bme280.get_pressure())))
            sakuraio.send()
            print("Send Data")
            time.sleep(WAIT)

    except Exception as e:
        print(e)
Ejemplo n.º 5
0
class Sensors:
    # BME280 temperature/pressure/humidity sensor
    bme280 = BME280()

    def __init__(self):
        print("[SENS] Initializing")

    def humidity(self):
        h = self.bme280.get_humidity()
        print("[SENS] Humidity: {}".format(h))
        return h

    def temperature(self):
        t = self.bme280.get_temperature()
        print("[SENS] Temperature: {}".format(t))
        return t

    def cpu_temperature(self):
        process = Popen(['vcgencmd', 'measure_temp'],
                        stdout=PIPE,
                        universal_newlines=True)
        output, _error = process.communicate()
        t = float(output[output.index('=') + 1:output.rindex("'")])
        print("[SENS] CPU Temperature: {}".format(t))
        return t

    def lux(self):
        l = ltr559.get_lux()
        print("[SENS] Lux: {}".format(l))
        return l
Ejemplo n.º 6
0
    def __init__(self, client_id, host, port, username, password, prefix, use_pms5003, num_samples, use_gas):
        self.bme280 = BME280()

        self.prefix = prefix

        print('MQTT Address:', host + ':' + str(port))
        print('MQTT Credentials:', username, '/', password)
        print('MQTT Prefix:', prefix)
        print('MQTT Client ID:', client_id)
        print('Use PMS5003:', use_pms5003)
        print('Use Gas:', use_gas, flush=True)

        self.connection_error = None
        self.client = mqtt.Client(client_id=client_id)
        self.client.on_connect = self.__on_connect
        self.client.username_pw_set(username, password)
        self.client.connect(host, port)
        self.use_gas = use_gas
        self.client.loop_start()

        self.samples = collections.deque(maxlen=num_samples)
        self.latest_pms_readings = {}

        if use_pms5003:
            self.pm_thread = threading.Thread(target=self.__read_pms_continuously)
            self.pm_thread.daemon = True
            self.pm_thread.start()
Ejemplo n.º 7
0
    def __init__(self, temp = True, pressure = True, humidity = True, light = True, oxidised = True, reduced = True, nh3 = True, pm1 = True, pm10 = True, pm25 = True):
        self.__variables = {
            "temp" : temp,
            "pressure" : pressure,
            "humidity" : humidity,
            "light" : light,
            "oxidised" : oxidised,
            "reduced" : reduced,
            "nh3" : nh3,
            "pm1" : pm1,
            "pm25" : pm25,
            "pm10" : pm10
        }

        # Pre-load sensor packages
        if (self.__variables['temp'] or self.__variables['pressure'] or self.__variables['humidity']):
            bus = SMBus(1)
            self.bme280 = BME280(i2c_dev=bus)
            # Take initial reading then allow time to get it to 
            self.init_temp_reading = self.bme280.get_temperature()
            self.init_pressure = self.bme280.get_pressure()
            self.init_humidity = self.bme280.get_humidity()
            time.sleep(1)
        if self.__variables['light']:
            self.ltr559 = LTR559()
        if (self.__variables['pm1'] or self.__variables['pm25'] or self.__variables['pm10']):
            self.pms5003 = PMS5003()

        # Define output
        self.output_dict = {
            'script_version' : '0.0.1',
            'device_name' : 'my_device'
        }
Ejemplo n.º 8
0
def output():

    # Get Temperature, pressure and humidity
    bus = SMBus(1)
    bme280 = BME280(i2c_dev=bus)

    cpu_temps = [get_cpu_temperature()] * 5
    factor = 0.8

    raw_temp = bme280.get_temperature()
    cpu_temp = get_cpu_temperature()
    cpu_temps = cpu_temps[1:] + [cpu_temp]
    avg_cpu_temp = sum(cpu_temps) / float(len(cpu_temps))
    compTemp = raw_temp - ((avg_cpu_temp - raw_temp) / factor)

    pressure = bme280.get_pressure()
    humidity = bme280.get_humidity()

    # Get gases
    gases = gas.read_all()
    nh3 = gases.nh3
    no2 = gases.oxidising

    # Get light and proximity
    light = ltr559.get_lux()
    proxim = ltr559.get_proximity()

    # Calculate current time as string
    curTime = time.strftime("%d/%m/%y,%H:%M", time.localtime())

    return compTemp, humidity, nh3, no2, light, proxim, pressure, curTime
Ejemplo n.º 9
0
    def __init__(self,
                 io_id,
                 io_user,
                 io_key,
                 frequency,
                 port=1883,
                 battery=False):
        # Turn sensors on/off
        self.sensor_on = True

        # Save variables passed for use in other methods
        self.io_id = io_id
        self.io_user = io_user
        self.io_key = io_key
        self.update_frequency = frequency
        self.port = port
        self.battery = battery

        i2c = I2C(0, I2C.MASTER, pins=('P4', 'P5'))
        self.sensor = BME280(i2c=i2c)
        utime.sleep_ms(100)
        logging("Weather MQTT client is ready.")

        if battery:
            self.apin = ADC().channel(pin='P13')
Ejemplo n.º 10
0
 def __init__(self, id="", unit="bme280", sda="P9", scl="P10", freq=5):
     self.sensor_id = id
     self.info = dict(
         id = self.sensor_id,
         type =  unit,
         label='BME280',
         freq = freq,
         data = dict(
             temperature=dict(
                 uom='°C',
                 label='Temperature'
             ),    
             pressure=dict(
                 uom='hPa',
                 label='Pressure'
             ),    
             humidity=dict(
                 uom='%',
                 label='Humidity'
             )
         )
     )
     global bme280
     if (bme280):
         self.bme280 = bme280
     else:
         self.i2c = I2C(0, I2C.MASTER, pins=(sda, scl))
         self.bme280 = BME280(i2c=self.i2c)
         bme280 = self.bme280
Ejemplo n.º 11
0
def test_setup_forced_mode():
    from tools import SMBusFakeDevice
    smbus = mock.Mock()
    smbus.SMBus = SMBusFakeDevice
    sys.modules['smbus'] = smbus
    from bme280 import BME280
    bme280 = BME280()
    bme280.setup(mode="forced")
Ejemplo n.º 12
0
def test_setup_mock_present():
    from tools import SMBusFakeDevice
    smbus = mock.Mock()
    smbus.SMBus = SMBusFakeDevice
    sys.modules['smbus'] = smbus
    from bme280 import BME280
    bme280 = BME280()
    bme280.setup()
Ejemplo n.º 13
0
 def __init__(self, i2c, address=0x76):
     if not isinstance(i2c, machine.I2C):
         raise TypeError("I2C object required.")
     from bme280 import BME280
     self.bme = BME280(i2c=i2c, address=address)
     self.t = None
     self.h = None
     self.p = None
Ejemplo n.º 14
0
    def __init__(self):
        # BME280 temperature/pressure/humidity sensor
        self.bme280 = BME280()
        # Light sensor
        self.ltr559 = LTR559()
        self.noise = Noise()

        self.cpu_temps = None
        self.factor = 2.25
class EnvironmentMetrics:
    # Adjust this to calibrate temperature
    # TEMP_TUNING_FACTOR = 0.8 # This is the tuning factor if it is the box
    TEMP_TUNING_FACTOR = 3.0  # This is the tuningh factor for out of the box (for now)

    # bme280 temperature/pressure/humidity sensor
    BME280_INSTANCE = BME280()
    # ltr559 light sensor
    LTR559_INSTANCE = LTR559()
    # PMS5003 data from air quality sensor
    PMS5003_INSTANCE = PMS5003()

    def __init__(self):
        pass

    @classmethod
    def get_cpu_temperature(cls):
        process = Popen(['vcgencmd', 'measure_temp'],
                        stdout=PIPE,
                        universal_newlines=True)
        output, _error = process.communicate()
        return float(output[output.index('=') + 1:output.rindex("'")])

    @classmethod
    def calibrated_temp(cls):
        cpu_temp = cls.get_cpu_temperature()
        cpu_temps = [cls.get_cpu_temperature()] * 5

        # Smooth out with some averaging to decrease jitter
        cpu_temps = cpu_temps[1:] + [cpu_temp]
        avg_cpu_temp = sum(cpu_temps) / float(len(cpu_temps))

        raw_temp = cls.BME280_INSTANCE.get_temperature()
        data = raw_temp - ((avg_cpu_temp - raw_temp) / cls.TEMP_TUNING_FACTOR)
        return data

    @classmethod
    def build_metrics_dict(cls):
        pms_data = cls.PMS5003_INSTANCE.read()
        return {
            "temperature": cls.calibrated_temp(),
            "pressure": cls.BME280_INSTANCE.get_pressure(),
            "humidity": cls.BME280_INSTANCE.get_humidity(),
            "light": cls.LTR559_INSTANCE.get_lux(),
            "gas_oxidizing": gas.read_oxidising(),
            "gas_reducing": gas.read_reducing(),
            "gas_nh3": gas.read_nh3(),
            "pm_ug_per_m3_1_0": pms_data.pm_ug_per_m3(1.0),
            "pm_ug_per_m3_2_5": pms_data.pm_ug_per_m3(2.5),
            "pm_ug_per_m3_10": pms_data.pm_ug_per_m3(10),
            "pm_per_dl_0_3": pms_data.pm_per_1l_air(0.3),
            "pm_per_dl_0_5": pms_data.pm_per_1l_air(0.5),
            "pm_per_dl_1_0": pms_data.pm_per_1l_air(1.0),
            "pm_per_dl_2_5": pms_data.pm_per_1l_air(2.5),
            "pm_per_dl_5_0": pms_data.pm_per_1l_air(5.0),
            "pm_per_dl_10_0": pms_data.pm_per_1l_air(10.0)
        }
Ejemplo n.º 16
0
def bme280_init():
    from bme280 import BME280
    try:
        i2c = i2c_init(1)
        bme = BME280(i2c=i2c)
        print(bme.values)
        return bme
    except Exception as e:
        print("bme280_init() Exception: {0}".format(e))
Ejemplo n.º 17
0
    def __init__(self, comp_factor: float = 1.2) -> None:
        self.bus = SMBus(1)

        # Create BME280 (temp, humidity and pressure sensor) instance
        self.bme280 = BME280(i2c_dev=self.bus)

        # Create PMS5003 dust sensor instance
        self.pms5003 = PMS5003()
        self.comp_factor = comp_factor
Ejemplo n.º 18
0
 def check(self):
     if self.config_bme == False:
         if BME280_I2CADDR in self.i2c.scan():
             self.bme = BME280(i2c=self.i2c)
             self.config_bme = True
     if self.config_qmcx == False:
         if QMCX983_I2CADDR in self.i2c.scan():
             self.qmcx = QMCX983(i2c=self.i2c)
             self.config_qmcx = True
 def __init__(self, name="bme280", device=None):
     super().__init__(id="bme280", name=name, type="sensor")
     self.device = device
     self.i2c = I2C(scl=Pin(5), sda=Pin(4))
     self.bme280 = BME280(i2c=self.i2c)
     self.temperature = HomieNodeProperty(
         id="temperature",
         name="temperature",
         unit="°C",
         settable=False,
         datatype=FLOAT,
         default=0,
     )
     self.add_property(self.temperature)
     self.humidity = HomieNodeProperty(
         id="humidity",
         name="humidity",
         unit="%",
         settable=False,
         datatype=FLOAT,
         default=0,
     )
     self.add_property(self.humidity)
     self.pressure = HomieNodeProperty(
         id="pressure",
         name="pressure",
         unit="Pa",
         settable=False,
         datatype=FLOAT,
         default=0,
     )
     self.add_property(self.pressure)
     self.uptime = HomieNodeProperty(
         id="uptime",
         name="uptime",
         settable=False,
         datatype=STRING,
         default="PT0S"
     )
     self.add_property(self.uptime)
     self.ip = HomieNodeProperty(
         id="ip",
         name="ip",
         settable=False,
         datatype=STRING,
         default="",
     )
     self.add_property(self.ip)
     self.led = Pin(0, Pin.OUT)
     self.online_led = Pin(12, Pin.OUT)
     self.online_led.off()
     self.last_online = time.time()
     self.start = time.time()
     print("start time", self.start)
     loop = get_event_loop()
     loop.create_task(self.update_data())
Ejemplo n.º 20
0
    def _get_device(self):
        if self._device:
            return self._device

        from smbus import SMBus
        from bme280 import BME280

        self._bus = SMBus(self.port)
        self._device = BME280(i2c_dev=self._bus)
        return self._device
Ejemplo n.º 21
0
def main(args):
    host = args.host
    rootCAPath = args.rootCAPath
    certificatePath = args.certificatePath
    privateKeyPath = args.privateKeyPath
    clientId = args.clientId
    topic = args.topic

    if not args.certificatePath or not args.privateKeyPath:
        parser.error("Missing credentials for authentication.")
        exit(2)

    port = 8883

    configureLogging()

    # Init AWSIoTMQTTClient
    myAWSIoTMQTTClient = None
    myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId)
    myAWSIoTMQTTClient.configureEndpoint(host, port)
    myAWSIoTMQTTClient.configureCredentials(rootCAPath, privateKeyPath,
                                            certificatePath)

    configMQTTClient(myAWSIoTMQTTClient)

    # Connect and subscribe to AWS IoT
    myAWSIoTMQTTClient.connect()
    myAWSIoTMQTTClient.subscribe(topic, 1, customCallback)
    time.sleep(2)

    # Sensor objects
    bus = SMBus(1)
    bme280 = BME280(i2c_dev=bus)
    pms5003 = PMS5003()

    # Publish to the same topic in a loop forever
    while True:
        try:
            message = {}
            message_data = read_bme280(bme280, ltr559)
            pms_values = read_pms5003(pms5003)
            message_data.update(pms_values)
            message['data'] = message_data

            message['device_id'] = 'enviro'
            now = datetime.utcnow()  # get date and time
            current_time = now.strftime('%Y-%m-%dT%H:%M:%SZ')
            message['time'] = current_time
            messageJson = json.dumps(message)
            myAWSIoTMQTTClient.publish(topic, messageJson, 1)
            print('Published topic %s: %s\n' % (topic, messageJson))
            time.sleep(60)  # Once a minute
        except Exception as e:
            print(e)
Ejemplo n.º 22
0
def get_sensor_readings():
    i2c = machine.I2C(scl=machine.Pin(config.SCL_PIN),
                      sda=machine.Pin(config.SDA_PIN))
    bme280 = BME280(i2c=i2c)
    temperature, _, humidity = bme280.read_compensated_data()

    return json.dumps({
        'temperature': temperature,
        'humidity': humidity,
        'heat_index': bme280.heat_index,
        'dew_point': bme280.dew_point
    })
Ejemplo n.º 23
0
    def __init__(self):
        self.ccs811 = CCS811()
        self.bme280 = BME280()
        p, t, h = self.bme280.get()
        self.ccs811.compensate(h, t)

        self.data_co2 = np.zeros(int(X_LIMIT/RESOLUSION), dtype=int)
        self.data_t = np.zeros(int(X_LIMIT/RESOLUSION), dtype=int)
        self.data_h = np.zeros(int(X_LIMIT/RESOLUSION), dtype=int)
        self.data_p = np.zeros(int(X_LIMIT/RESOLUSION), dtype=int)

        self.root = tkinter.Tk()
        self.root.wm_title("Embedding in Tk anim")

        self.fig = Figure()
        # FuncAnimationより前に呼ぶ必要がある
        canvas = FigureCanvasTkAgg(self.fig, master=self.root)  # A tk.DrawingArea.

        x = np.arange(0, X_LIMIT, RESOLUSION)  # x軸(固定の値)
        self.l = np.arange(0, X_LIMIT, RESOLUSION)  # 表示期間(FuncAnimationで指定する関数の引数になる)
        plt_co2 = self.fig.add_subplot(211)
        plt_co2.set_ylim([0, 4000])
        self.line_co2, = plt_co2.plot(x, self.data_co2, 'C3', label="CO2 ppm")

        h0, l0 = plt_co2.get_legend_handles_labels()
        plt_co2.legend(h0, l0, loc='upper left')

        plt_t = self.fig.add_subplot(212)
        plt_t.set_ylim([-10, 50])
        self.line_t, = plt_t.plot(x, self.data_t, 'C1', label="Celsius")

        plt_h = plt_t.twinx()
        plt_h.set_ylim([0, 100])
        self.line_h, = plt_h.plot(x, self.data_h, 'C0', label="humidity %")

        plt_p = plt_t.twinx()
        plt_p.set_ylim([900, 1200])
        self.line_p, = plt_p.plot(x, self.data_p, 'C2', label="pressure hPa")

        h1, l1 = plt_t.get_legend_handles_labels()
        h2, l2 = plt_h.get_legend_handles_labels()
        h3, l3 = plt_p.get_legend_handles_labels()
        plt_t.legend(h1+h2+h3, l1+l2+l3, loc='upper left')

        self.ani = animation.FuncAnimation(self.fig, self.animate, self.l,
            init_func=self.init, interval=int(1000*RESOLUSION), blit=False,
            )

        toolbar = NavigationToolbar2Tk(canvas, self.root)
        canvas.get_tk_widget().pack(fill='both')

        button = tkinter.Button(master=self.root, text="Quit", command=self.quit)
        button.pack()
Ejemplo n.º 24
0
    def __init__(self):
        # BME280 temperature/pressure/humidity sensor
        self.__bme280 = BME280()

        # PMS5003 particulate sensor
        self.__pms5003 = PMS5003()

        self.__ltr559 = ltr559

        self.__lcd = EnviroLCD()
        self.__cpu_temp_history = deque([self.__get_cpu_temperature()] * 15)

        self.__update_proc = None
Ejemplo n.º 25
0
async def main():
    parser = argparse.ArgumentParser(
        description=
        "Data collector which sends sensor measurements to Azure IoT HUB")
    parser.add_argument("--nolcd",
                        action='store_true',
                        help="Skip LCD printout")
    args = parser.parse_args()
    if args.nolcd:
        print("No LCD")

    try:
        bme280 = BME280()
        led = Led()
        lcd = None
        if not args.nolcd:
            lcd = LCD()

        (chip_id, chip_version) = bme280.readID()
        print(f"Started, chip_id={chip_id}, chip_version={chip_version}")

        conn_str = os.getenv("DEV_BME_CONN_STR")
        device_client = IoTHubDeviceClient.create_from_connection_string(
            conn_str)
        await device_client.connect()

        while True:
            temperature, pressure, humidity = bme280.readAll()
            measTime = datetime.now().isoformat()
            measRow = f'{{"Temperature":{temperature:0.2f},"Pressure":{pressure:0.2f},"Humidity":{humidity:0.2f}}}'

            print(f"Sending message: {measRow}")
            await device_client.send_message(measRow)

            if not args.nolcd:
                lcdOut = f"T:{temperature:0.1f}C {pressure:0.1f}hPa\nH:{humidity:0.1f}%"
                lcd.clear()
                lcd.setCursor(0, 0)
                lcd.message(lcdOut)

            led.blinkLed()
            sleep(2 * 60)

    except KeyboardInterrupt:
        print("exiting...")
        await device_client.disconnect()
        led.close()
        if not args.nolcd:
            lcd.clear()
            lcd.setCursor(0, 0)
            lcd.destroy()
Ejemplo n.º 26
0
    def __init__(self, client_id, host, port, username, password, prefix,
                 use_pms5003, num_samples):
        self.bme280 = BME280()
        self.pms5003 = use_pms5003 and PMS5003() or None

        self.prefix = prefix

        self.connection_error = None
        self.client = mqtt.Client(client_id=client_id)
        self.client.on_connect = self.__on_connect
        self.client.username_pw_set(username, password)
        self.client.connect(host, port)

        self.samples = collections.deque(maxlen=num_samples)
    def start(self):
        """
        Getting the bus
        """
        if self.bus is None:
            raise KeyError("Bus missing for BME280Sensor")

        # Initialize the hardware driver.
        try:
            self.driver = BME280(address=self.address, i2c=self.bus.adapter)
            return True

        except Exception as ex:
            log.exception('BME280 hardware driver failed')
Ejemplo n.º 28
0
 def __init__(self):
     '''Constructor'''
     logging.info('__init__()')
     # BME280 temperature/pressure/humidity sensor
     # Tuning factor for compensation. Decrease this number to adjust the
     # temperature down, and increase to adjust up
     self.factor = 1
     self.bme280 = BME280()
     self.send_data = False
     self.cpu_temp = 0.0
     # Default of 10 minutes
     self.wait_time = 10 * Temperature.SECONDS_PER_MINUTE
     self.server_address = ''
     self.temperature = 0
Ejemplo n.º 29
0
def bme():
	import time
	from bme280 import BME280
	
	try:
	    from smbus2 import SMBus
	except ImportError:
	    from smbus import SMBus
	
	bus = SMBus(1)
	bme280 = BME280(i2c_dev=bus)
	
	temperature = bme280.get_temperature()
	pressure = bme280.get_pressure()
	humidity = bme280.get_humidity()
    def __init__(self):
        self.pms5003 = PMS5003()
        self.bus = SMBus(1)
        self.bme280 = BME280(i2c_dev=self.bus)
        self.bme280.get_pressure(
        )  # prime bme sensor as first reading not accurate
        self.msgId = 0
        self.nextRead = None
        self.avg = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

        self.pid = os.getpid()
        self.py = psutil.Process(self.pid)

        # pause for a moment to allow the pms5003 to settle
        time.sleep(1.0)