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.
64 www = urllib.request.urlopen(
65 "http://10.0.0.75/~pi/outside_temp",
68 current_temp = www.read().decode("utf-8")
69 current_temp = float(current_temp)
72 current_temp = round(current_temp)
74 logger.warning('Timed out reading 10.0.0.75/~pi/outside_temp?!')
80 # Get a weather forecast for Bellevue.
81 www = urllib.request.urlopen(
82 "https://forecast.weather.gov/MapClick.php?lat=47.652775&lon=-122.170716"
84 forecast_response = www.read()
87 soup = BeautifulSoup(forecast_response, "html.parser")
88 forecast = soup.find(id='detailed-forecast-body')
89 parser = dp.DateParser()
94 for (day, txt) in zip(
95 forecast.find_all('b'),
96 forecast.find_all(class_='col-sm-10 forecast-text')
100 dt = parser.parse(day.get_text())
103 assert dt is not None
105 # Compute sunrise/sunset times on dt.
106 city = astral.LocationInfo(
107 "Bellevue", "USA", "US/Pacific", 47.653, -122.171
109 s = sun(city.observer, date=dt, tzinfo=pytz.timezone("US/Pacific"))
110 sunrise = s['sunrise']
113 if dt.date() == now.date() and not said_temp and current_temp is not None:
114 blurb = f'{day.get_text()}: The current outside tempterature is {current_temp}. '
115 blurb += txt.get_text()
118 blurb = f'{day.get_text()}: {txt.get_text()}'
119 blurb = text_utils.wrap_string(blurb, 80)
121 if dt.date() in self.forecasts:
122 self.forecasts[dt.date()].description += '\n' + blurb
124 self.forecasts[dt.date()] = WeatherForecast(
133 if persistent.was_file_written_within_n_seconds(
134 config.config['weather_forecast_cachefile'],
135 config.config['weather_forecast_stalest_acceptable'].total_seconds(),
138 with open(config.config['weather_forecast_cachefile'], 'rb') as rf:
139 weather_data = pickle.load(rf)
140 return cls(weather_data)
145 with open(config.config['weather_forecast_cachefile'], 'wb') as wf:
149 pickle.HIGHEST_PROTOCOL,