view weatherlog/types.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 b5625b531d2d
children
line wrap: on
line source

"""Basic datatypes for the weather station.
"""

import datetime
import typing as t

import attr
import pytz


def _utc_now() -> datetime.datetime:
    """utcnow, but timezone-aware."""
    return datetime.datetime.now(tz=pytz.UTC)


T = t.TypeVar('T')


@attr.s(auto_attribs=True, frozen=True, slots=True)
class Reading(object):
    """A single reading from a temperature/humidity sensor."""

    # The timestamp of the reading.
    sample_time: datetime.datetime

    # The temperature, in degrees Celsius.
    temp_c: float

    # The relative humidity, in percent.
    rh_pct: float

    # The atmospheric pressure in kilopascals, if known.
    pressure_kpa: t.Optional[float] = None

    @classmethod
    def from_now(cls: t.Type[T], **kwargs) -> T:
        """Creates a new reading taken at the current time."""
        return cls(sample_time=_utc_now(), **kwargs)

    def as_dict(self):
        return filter_nones(attr.asdict(self, recurse=False))


def filter_nones(d: t.Dict[str, t.Optional[object]]) -> t.Dict[str, object]:
    return {k: v for (k, v) in d.items() if v is not None}