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