view weatherlog/reader.py @ 26:ec575bfd68cd v0.4.0

Reduce noise by oversampling a bunch!
author Paul Fisher <paul@pfish.zone>
date Sun, 02 Mar 2025 19:33:38 -0500
parents 1ae7bd2566ef
children e5f285ea68f8
line wrap: on
line source

"""A module for reading data from the actual temperature sensor.

You should probably assume that this is wildly thread-unsafe.
"""

import abc
import time
import typing as t

import bme280
import smbus2

from . import types


class Reader(metaclass=abc.ABCMeta):
    """Interface for a thing which reads temperatures."""

    @abc.abstractmethod
    def read(self) -> types.Reading:
        """Reads a value from the weather sensor."""
        raise NotImplementedError()



class BME280Reader:

    def __init__(self, bus_id: int = 1, address: int = 0x77):
        self.bus = smbus2.SMBus(bus_id)
        # Maybe this will prevent some hangs?
        # I saw it somewhere but don't remember where...
        time.sleep(1)
        self.address = address
        self.calibration = bme280.load_calibration_params(self.bus, address)

    def read(self) -> types.Reading:
        reading = bme280.sample(
            self.bus, self.address, self.calibration,
            oversampling=bme280.oversampling.x4)
        return types.Reading.from_now(
            temp_c=reading.temperature,
            rh_pct=reading.humidity,
            pressure_kpa=reading.pressure / 10)