view weather_server/locations.py @ 13:4eaa9d69c4e2

Extremely basic version of the graph drawer.
author Paul Fisher <paul@pfish.zone>
date Sun, 06 Oct 2019 17:09:23 -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)