Make subdirs type clean too.
[python_utils.git] / cached / weather_forecast.py
1 #!/usr/bin/env python3
2
3 import datetime
4 import logging
5 import os
6 import urllib.request
7 from dataclasses import dataclass
8 from typing import Any
9
10 import astral  # type: ignore
11 import pytz
12 from astral.sun import sun  # type: ignore
13 from bs4 import BeautifulSoup  # type: ignore
14 from overrides import overrides
15
16 import argparse_utils
17 import config
18 import dateparse.dateparse_utils as dp
19 import datetime_utils
20 import persistent
21 import smart_home.thermometers as temps
22 import text_utils
23
24 logger = logging.getLogger(__name__)
25
26 cfg = config.add_commandline_args(
27     f'Cached Weather Forecast ({__file__})',
28     'Arguments controlling detailed weather rendering',
29 )
30 cfg.add_argument(
31     '--weather_forecast_cachefile',
32     type=str,
33     default=f'{os.environ["HOME"]}/cache/.weather_forecast_cache',
34     metavar='FILENAME',
35     help='File in which to cache weather data',
36 )
37 cfg.add_argument(
38     '--weather_forecast_stalest_acceptable',
39     type=argparse_utils.valid_duration,
40     default=datetime.timedelta(seconds=7200),  # 2 hours
41     metavar='DURATION',
42     help='Maximum acceptable age of cached data.  If zero, forces a refetch',
43 )
44
45
46 @dataclass
47 class WeatherForecast:
48     date: datetime.date  # The date
49     sunrise: datetime.datetime  # Sunrise datetime
50     sunset: datetime.datetime  # Sunset datetime
51     description: str  # Textual description of weather
52
53
54 @persistent.persistent_autoloaded_singleton()  # type: ignore
55 class CachedDetailedWeatherForecast(persistent.Persistent):
56     def __init__(self, forecasts=None):
57         if forecasts is not None:
58             self.forecasts = forecasts
59             return
60
61         now = datetime_utils.now_pacific()
62         self.forecasts = {}
63
64         # Ask the raspberry pi about the outside temperature.
65         current_temp = temps.ThermometerRegistry().read_temperature(
66             'house_outside', convert_to_fahrenheit=True
67         )
68
69         # Get a weather forecast for Bellevue.
70         www = urllib.request.urlopen(
71             "https://forecast.weather.gov/MapClick.php?lat=47.652775&lon=-122.170716"
72         )
73         forecast_response = www.read()
74         www.close()
75
76         soup = BeautifulSoup(forecast_response, "html.parser")
77         forecast = soup.find(id='detailed-forecast-body')
78         parser = dp.DateParser()
79
80         said_temp = False
81         last_dt = now
82         dt = now
83         for (day, txt) in zip(
84             forecast.find_all('b'), forecast.find_all(class_='col-sm-10 forecast-text')
85         ):
86             last_dt = dt
87             try:
88                 dt = parser.parse(day.get_text())
89             except Exception:
90                 dt = last_dt
91             assert dt is not None
92
93             # Compute sunrise/sunset times on dt.
94             city = astral.LocationInfo(
95                 "Bellevue", "USA", "US/Pacific", 47.653, -122.171
96             )
97             s = sun(city.observer, date=dt, tzinfo=pytz.timezone("US/Pacific"))
98             sunrise = s['sunrise']
99             sunset = s['sunset']
100
101             if dt.date() == now.date() and not said_temp and current_temp is not None:
102                 blurb = f'{day.get_text()}: The current outside tempterature is {current_temp}. '
103                 blurb += txt.get_text()
104                 said_temp = True
105             else:
106                 blurb = f'{day.get_text()}: {txt.get_text()}'
107             blurb = text_utils.wrap_string(blurb, 80)
108
109             if dt.date() in self.forecasts:
110                 self.forecasts[dt.date()].description += '\n' + blurb
111             else:
112                 self.forecasts[dt.date()] = WeatherForecast(
113                     date=dt,
114                     sunrise=sunrise,
115                     sunset=sunset,
116                     description=blurb,
117                 )
118
119     @classmethod
120     @overrides
121     def load(cls) -> Any:
122         if persistent.was_file_written_within_n_seconds(
123             config.config['weather_forecast_cachefile'],
124             config.config['weather_forecast_stalest_acceptable'].total_seconds(),
125         ):
126             import pickle
127
128             with open(config.config['weather_forecast_cachefile'], 'rb') as rf:
129                 weather_data = pickle.load(rf)
130                 return cls(weather_data)
131         return None
132
133     @overrides
134     def save(self) -> bool:
135         import pickle
136
137         with open(config.config['weather_forecast_cachefile'], 'wb') as wf:
138             pickle.dump(
139                 self.forecasts,
140                 wf,
141                 pickle.HIGHEST_PROTOCOL,
142             )
143         return True