summaryrefslogtreecommitdiff
path: root/cached/weather_forecast.py
blob: b8a20ed8caa04553f01225a5a2f8f57866858ea7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
#!/usr/bin/env python3

# © Copyright 2021-2022, Scott Gasch

"""How's the weather going to be tomorrow?"""

import datetime
import logging
import os
import urllib.request
from dataclasses import dataclass
from typing import Any

import astral  # type: ignore
import pytz
from astral.sun import sun  # type: ignore
from bs4 import BeautifulSoup  # type: ignore
from overrides import overrides

import argparse_utils
import config
import dateparse.dateparse_utils as dp
import datetime_utils
import persistent
import smart_home.thermometers as temps
import text_utils

logger = logging.getLogger(__name__)

cfg = config.add_commandline_args(
    f'Cached Weather Forecast ({__file__})',
    'Arguments controlling detailed weather rendering',
)
cfg.add_argument(
    '--weather_forecast_cachefile',
    type=str,
    default=f'{os.environ["HOME"]}/cache/.weather_forecast_cache',
    metavar='FILENAME',
    help='File in which to cache weather data',
)
cfg.add_argument(
    '--weather_forecast_stalest_acceptable',
    type=argparse_utils.valid_duration,
    default=datetime.timedelta(seconds=7200),  # 2 hours
    metavar='DURATION',
    help='Maximum acceptable age of cached data.  If zero, forces a refetch',
)


@dataclass
class WeatherForecast:
    date: datetime.date  # The date
    sunrise: datetime.datetime  # Sunrise datetime
    sunset: datetime.datetime  # Sunset datetime
    description: str  # Textual description of weather


@persistent.persistent_autoloaded_singleton()  # type: ignore
class CachedDetailedWeatherForecast(persistent.Persistent):
    def __init__(self, forecasts=None):
        if forecasts is not None:
            self.forecasts = forecasts
            return

        now = datetime_utils.now_pacific()
        self.forecasts = {}

        # Ask the raspberry pi about the outside temperature.
        current_temp = temps.ThermometerRegistry().read_temperature(
            'house_outside', convert_to_fahrenheit=True
        )

        # Get a weather forecast for Bellevue.
        www = urllib.request.urlopen(
            "https://forecast.weather.gov/MapClick.php?lat=47.652775&lon=-122.170716"
        )
        forecast_response = www.read()
        www.close()

        soup = BeautifulSoup(forecast_response, "html.parser")
        forecast = soup.find(id='detailed-forecast-body')
        parser = dp.DateParser()

        said_temp = False
        last_dt = now
        dt = now
        for (day, txt) in zip(
            forecast.find_all('b'),
            forecast.find_all(class_='col-sm-10 forecast-text'),
        ):
            last_dt = dt
            try:
                dt = parser.parse(day.get_text())
            except Exception:
                dt = last_dt
            assert dt is not None

            # Compute sunrise/sunset times on dt.
            city = astral.LocationInfo("Bellevue", "USA", "US/Pacific", 47.653, -122.171)
            s = sun(city.observer, date=dt, tzinfo=pytz.timezone("US/Pacific"))
            sunrise = s['sunrise']
            sunset = s['sunset']

            if dt.date() == now.date() and not said_temp and current_temp is not None:
                blurb = f'{day.get_text()}: The current outside tempterature is {current_temp}. '
                blurb += txt.get_text()
                said_temp = True
            else:
                blurb = f'{day.get_text()}: {txt.get_text()}'
            blurb = text_utils.wrap_string(blurb, 80)

            if dt.date() in self.forecasts:
                self.forecasts[dt.date()].description += '\n' + blurb
            else:
                self.forecasts[dt.date()] = WeatherForecast(
                    date=dt,
                    sunrise=sunrise,
                    sunset=sunset,
                    description=blurb,
                )

    @classmethod
    @overrides
    def load(cls) -> Any:
        if persistent.was_file_written_within_n_seconds(
            config.config['weather_forecast_cachefile'],
            config.config['weather_forecast_stalest_acceptable'].total_seconds(),
        ):
            import pickle

            with open(config.config['weather_forecast_cachefile'], 'rb') as rf:
                weather_data = pickle.load(rf)
                return cls(weather_data)
        return None

    @overrides
    def save(self) -> bool:
        import pickle

        with open(config.config['weather_forecast_cachefile'], 'wb') as wf:
            pickle.dump(
                self.forecasts,
                wf,
                pickle.HIGHEST_PROTOCOL,
            )
        return True