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
12 from overrides import overrides
18 import dateparse.dateparse_utils as dp
22 logger = logging.getLogger(__name__)
24 cfg = config.add_commandline_args(
25 f'Cached Weather Forecast ({__file__})',
26 'Arguments controlling detailed weather rendering'
29 '--weather_forecast_cachefile',
31 default=f'{os.environ["HOME"]}/cache/.weather_forecast_cache',
33 help='File in which to cache weather data'
36 '--weather_forecast_stalest_acceptable',
37 type=argparse_utils.valid_duration,
38 default=datetime.timedelta(seconds=7200), # 2 hours
40 help='Maximum acceptable age of cached data. If zero, forces a refetch'
45 class WeatherForecast:
46 date: datetime.date # The date
47 sunrise: datetime.datetime # Sunrise datetime
48 sunset: datetime.datetime # Sunset datetime
49 description: str # Textual description of weather
52 @persistent.persistent_autoloaded_singleton()
53 class CachedDetailedWeatherForecast(object):
54 def __init__(self, forecasts = None):
55 if forecasts is not None:
56 self.forecasts = forecasts
59 now = datetime_utils.now_pacific()
62 # Ask the raspberry pi about the outside temperature.
65 www = urllib.request.urlopen(
66 "http://10.0.0.75/~pi/outside_temp",
69 current_temp = www.read().decode("utf-8")
70 current_temp = float(current_temp)
73 current_temp = round(current_temp)
75 logger.warning('Timed out reading 10.0.0.75/~pi/outside_temp?!')
81 # Get a weather forecast for Bellevue.
82 www = urllib.request.urlopen(
83 "https://forecast.weather.gov/MapClick.php?lat=47.652775&lon=-122.170716"
85 forecast_response = www.read()
88 soup = BeautifulSoup(forecast_response, "html.parser")
89 forecast = soup.find(id='detailed-forecast-body')
90 parser = dp.DateParser()
95 for (day, txt) in zip(
96 forecast.find_all('b'),
97 forecast.find_all(class_='col-sm-10 forecast-text')
101 dt = parser.parse(day.get_text())
104 assert dt is not None
106 # Compute sunrise/sunset times on dt.
107 city = astral.LocationInfo(
108 "Bellevue", "USA", "US/Pacific", 47.653, -122.171
110 s = sun(city.observer, date=dt, tzinfo=pytz.timezone("US/Pacific"))
111 sunrise = s['sunrise']
114 if dt.date() == now.date() and not said_temp and current_temp is not None:
115 blurb = f'{day.get_text()}: The current outside tempterature is {current_temp}. '
116 blurb += txt.get_text()
119 blurb = f'{day.get_text()}: {txt.get_text()}'
120 blurb = text_utils.wrap_string(blurb, 80)
122 if dt.date() in self.forecasts:
123 self.forecasts[dt.date()].description += '\n' + blurb
125 self.forecasts[dt.date()] = WeatherForecast(
135 if persistent.was_file_written_within_n_seconds(
136 config.config['weather_forecast_cachefile'],
137 config.config['weather_forecast_stalest_acceptable'].total_seconds(),
140 with open(config.config['weather_forecast_cachefile'], 'rb') as rf:
141 weather_data = pickle.load(rf)
142 return cls(weather_data)
148 with open(config.config['weather_forecast_cachefile'], 'wb') as wf:
152 pickle.HIGHEST_PROTOCOL,