3 from dataclasses import dataclass
9 import astral # type: ignore
10 from astral.sun import sun # type: ignore
11 from bs4 import BeautifulSoup # type: ignore
17 import dateparse.dateparse_utils as dp
21 logger = logging.getLogger(__name__)
23 cfg = config.add_commandline_args(
24 f'Cached Weather Forecast ({__file__})',
25 'Arguments controlling detailed weather rendering'
28 '--weather_forecast_cachefile',
30 default=f'{os.environ["HOME"]}/.weather_forecast_cache',
32 help='File in which to cache weather data'
35 '--weather_forecast_stalest_acceptable',
36 type=argparse_utils.valid_duration,
37 default=datetime.timedelta(seconds=7200), # 2 hours
39 help='Maximum acceptable age of cached data. If zero, forces a refetch'
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
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
58 now = datetime_utils.now_pacific()
61 # Ask the raspberry pi about the outside temperature.
62 www = urllib.request.urlopen(
63 "http://10.0.0.75/~pi/outside_temp"
65 current_temp = www.read().decode("utf-8")
66 current_temp = float(current_temp)
69 current_temp = round(current_temp)
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"
76 forecast_response = www.read()
79 soup = BeautifulSoup(forecast_response, "html.parser")
80 forecast = soup.find(id='detailed-forecast-body')
81 parser = dp.DateParser()
86 for (day, txt) in zip(
87 forecast.find_all('b'),
88 forecast.find_all(class_='col-sm-10 forecast-text')
92 dt = parser.parse(day.get_text())
97 # Compute sunrise/sunset times on dt.
98 city = astral.LocationInfo(
99 "Bellevue", "USA", "US/Pacific", 47.653, -122.171
101 s = sun(city.observer, date=dt, tzinfo=pytz.timezone("US/Pacific"))
102 sunrise = s['sunrise']
105 if dt.date() == now.date() and not said_temp:
106 blurb = f'{day.get_text()}: The current outside tempterature is {current_temp}. '
107 blurb += txt.get_text()
110 blurb = f'{day.get_text()}: {txt.get_text()}'
111 blurb = text_utils.wrap_string(blurb, 80)
113 if dt.date() in self.forecasts:
114 self.forecasts[dt.date()].description += '\n' + blurb
116 self.forecasts[dt.date()] = WeatherForecast(
125 if persistent.was_file_written_within_n_seconds(
126 config.config['weather_forecast_cachefile'],
127 config.config['weather_forecast_stalest_acceptable'].total_seconds(),
130 with open(config.config['weather_forecast_cachefile'], 'rb') as rf:
131 weather_data = pickle.load(rf)
132 return cls(weather_data)
137 with open(config.config['weather_forecast_cachefile'], 'wb') as wf:
141 pickle.HIGHEST_PROTOCOL,