view weather_server/locations.py @ 18:9d07dc5c3340

Make graph look nicer.
author Paul Fisher <paul@pfish.zone>
date Sat, 12 Oct 2019 21:02:02 -0400
parents f1ea183d28ba
children beb42c835c52
line wrap: on
line source

"""Manages the directory containing the various logs."""

import configparser
import pathlib
import typing as t

import attr
import pytz

from . import logfile
from . import types


CONFIG_FILE = 'config.ini'
LOG = 'log.bson'


@attr.s(frozen=True, slots=True)
class LocationInfo:
    name = attr.ib(type=str)
    tz_name = attr.ib(type=str)
    password = attr.ib(type=str)

    def timezone(self):
        try:
            return pytz.timezone(self.tz_name)
        except pytz.UnknownTimeZoneError:
            return pytz.UTC

    @classmethod
    def load(cls, config_file: pathlib.Path) -> 'LocationInfo':
        parser = configparser.ConfigParser(interpolation=None)
        parser.read(config_file)
        return LocationInfo(
            name=parser.get('location', 'name', fallback='Weather station'),
            tz_name=parser.get('location', 'timezone', fallback='UTC'),
            password=parser.get('location', 'password'))


class Locations:
    def __init__(self, base: str):
        self._path = pathlib.Path(base)

    def paths(self) -> t.Tuple[str, ...]:
        return tuple(sorted(f.name for f in self._path.iterdir()))

    def get(self, name) -> t.Tuple[LocationInfo, logfile.Logger]:
        try:
            directory = self._path / name
            logger = logfile.Logger.create(str(directory / LOG))
            return (LocationInfo.load(directory / CONFIG_FILE), logger)
        except OSError:
            raise KeyError(name)