view weatherlog/reader.py @ 22:36ab505bc0a6 default tip

Bump version to v0.3.1.
author Paul Fisher <paul@pfish.zone>
date Tue, 01 Aug 2023 00:29:33 +0000
parents 1ae7bd2566ef
children
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)
        return types.Reading.from_now(
            temp_c=reading.temperature,
            rh_pct=reading.humidity,
            pressure_kpa=reading.pressure / 10)