3 from dataclasses import dataclass
10 import astral # type: ignore
11 from astral.sun import sun # type: ignore
12 from bs4 import BeautifulSoup # type: ignore
13 from overrides import overrides
19 import dateparse.dateparse_utils as dp
22 import smart_home.thermometers as temps
25 logger = logging.getLogger(__name__)
27 cfg = config.add_commandline_args(
28 f'Cached Weather Forecast ({__file__})',
29 'Arguments controlling detailed weather rendering'
32 '--weather_forecast_cachefile',
34 default=f'{os.environ["HOME"]}/cache/.weather_forecast_cache',
36 help='File in which to cache weather data'
39 '--weather_forecast_stalest_acceptable',
40 type=argparse_utils.valid_duration,
41 default=datetime.timedelta(seconds=7200), # 2 hours
43 help='Maximum acceptable age of cached data. If zero, forces a refetch'
48 class WeatherForecast:
49 date: datetime.date # The date
50 sunrise: datetime.datetime # Sunrise datetime
51 sunset: datetime.datetime # Sunset datetime
52 description: str # Textual description of weather
55 @persistent.persistent_autoloaded_singleton()
56 class CachedDetailedWeatherForecast(persistent.Persistent):
57 def __init__(self, forecasts = None):
58 if forecasts is not None:
59 self.forecasts = forecasts
62 now = datetime_utils.now_pacific()
65 # Ask the raspberry pi about the outside temperature.
66 current_temp = temps.ThermometerRegistry().read_temperature(
67 'house_outside', convert_to_fahrenheit=True
70 # Get a weather forecast for Bellevue.
71 www = urllib.request.urlopen(
72 "https://forecast.weather.gov/MapClick.php?lat=47.652775&lon=-122.170716"
74 forecast_response = www.read()
77 soup = BeautifulSoup(forecast_response, "html.parser")
78 forecast = soup.find(id='detailed-forecast-body')
79 parser = dp.DateParser()
84 for (day, txt) in zip(
85 forecast.find_all('b'),
86 forecast.find_all(class_='col-sm-10 forecast-text')
90 dt = parser.parse(day.get_text())
95 # Compute sunrise/sunset times on dt.
96 city = astral.LocationInfo(
97 "Bellevue", "USA", "US/Pacific", 47.653, -122.171
99 s = sun(city.observer, date=dt, tzinfo=pytz.timezone("US/Pacific"))
100 sunrise = s['sunrise']
103 if dt.date() == now.date() and not said_temp and current_temp is not None:
104 blurb = f'{day.get_text()}: The current outside tempterature is {current_temp}. '
105 blurb += txt.get_text()
108 blurb = f'{day.get_text()}: {txt.get_text()}'
109 blurb = text_utils.wrap_string(blurb, 80)
111 if dt.date() in self.forecasts:
112 self.forecasts[dt.date()].description += '\n' + blurb
114 self.forecasts[dt.date()] = WeatherForecast(
123 def load(cls) -> Any:
124 if persistent.was_file_written_within_n_seconds(
125 config.config['weather_forecast_cachefile'],
126 config.config['weather_forecast_stalest_acceptable'].total_seconds(),
129 with open(config.config['weather_forecast_cachefile'], 'rb') as rf:
130 weather_data = pickle.load(rf)
131 return cls(weather_data)
135 def save(self) -> bool:
137 with open(config.config['weather_forecast_cachefile'], 'wb') as wf:
141 pickle.HIGHEST_PROTOCOL,