7 from dataclasses import dataclass
10 import astral # type: ignore
12 from astral.sun import sun # type: ignore
13 from bs4 import BeautifulSoup # type: ignore
14 from overrides import overrides
18 import dateparse.dateparse_utils as dp
21 import smart_home.thermometers as temps
24 logger = logging.getLogger(__name__)
26 cfg = config.add_commandline_args(
27 f'Cached Weather Forecast ({__file__})',
28 'Arguments controlling detailed weather rendering',
31 '--weather_forecast_cachefile',
33 default=f'{os.environ["HOME"]}/cache/.weather_forecast_cache',
35 help='File in which to cache weather data',
38 '--weather_forecast_stalest_acceptable',
39 type=argparse_utils.valid_duration,
40 default=datetime.timedelta(seconds=7200), # 2 hours
42 help='Maximum acceptable age of cached data. If zero, forces a refetch',
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
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
61 now = datetime_utils.now_pacific()
64 # Ask the raspberry pi about the outside temperature.
65 current_temp = temps.ThermometerRegistry().read_temperature(
66 'house_outside', convert_to_fahrenheit=True
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"
73 forecast_response = www.read()
76 soup = BeautifulSoup(forecast_response, "html.parser")
77 forecast = soup.find(id='detailed-forecast-body')
78 parser = dp.DateParser()
83 for (day, txt) in zip(
84 forecast.find_all('b'),
85 forecast.find_all(class_='col-sm-10 forecast-text'),
89 dt = parser.parse(day.get_text())
94 # Compute sunrise/sunset times on dt.
95 city = astral.LocationInfo("Bellevue", "USA", "US/Pacific", 47.653, -122.171)
96 s = sun(city.observer, date=dt, tzinfo=pytz.timezone("US/Pacific"))
97 sunrise = s['sunrise']
100 if dt.date() == now.date() and not said_temp and current_temp is not None:
101 blurb = f'{day.get_text()}: The current outside tempterature is {current_temp}. '
102 blurb += txt.get_text()
105 blurb = f'{day.get_text()}: {txt.get_text()}'
106 blurb = text_utils.wrap_string(blurb, 80)
108 if dt.date() in self.forecasts:
109 self.forecasts[dt.date()].description += '\n' + blurb
111 self.forecasts[dt.date()] = WeatherForecast(
120 def load(cls) -> Any:
121 if persistent.was_file_written_within_n_seconds(
122 config.config['weather_forecast_cachefile'],
123 config.config['weather_forecast_stalest_acceptable'].total_seconds(),
127 with open(config.config['weather_forecast_cachefile'], 'rb') as rf:
128 weather_data = pickle.load(rf)
129 return cls(weather_data)
133 def save(self) -> bool:
136 with open(config.config['weather_forecast_cachefile'], 'wb') as wf:
140 pickle.HIGHEST_PROTOCOL,