2 # -*- coding: utf-8 -*-
4 # © Copyright 2021-2022, Scott Gasch
6 """How's the weather?"""
13 from dataclasses import dataclass
14 from typing import Any, List
16 from overrides import overrides
24 logger = logging.getLogger(__name__)
26 cfg = config.add_commandline_args(
27 f'Cached Weather Data List ({__file__})',
28 'Arguments controlling cached weather data',
31 '--weather_data_cachefile',
33 default=f'{os.environ["HOME"]}/cache/.weather_summary_cache',
35 help='File in which to cache weather data',
38 '--weather_data_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',
48 date: datetime.date # The date
49 high: float # The predicted high in F
50 low: float # The predicted low in F
51 precipitation_inches: float # Number of inches of precipitation / day
52 conditions: List[str] # Conditions per ~3h window
53 most_common_condition: str # The most common condition
54 icon: str # An icon to represent it
57 @persistent.persistent_autoloaded_singleton() # type: ignore
58 class CachedWeatherData(persistent.Persistent):
59 def __init__(self, weather_data=None):
60 if weather_data is not None:
61 self.weather_data = weather_data
63 self.weather_data = {}
81 now = datetime.datetime.now()
87 param = "id=5786882" # Bellevue, WA
88 key = "c0b160c49743622f62a9cd3cda0270b3"
89 www = urllib.request.urlopen(
90 f'http://api.openweathermap.org/data/2.5/weather?zip=98005,us&APPID={key}&units=imperial'
94 parsed_json = json.loads(response)
95 logger.debug(parsed_json)
96 dt = datetime.datetime.fromtimestamp(parsed_json["dt"]).date()
98 condition = parsed_json["weather"][0]["main"]
99 icon = icon_by_condition.get(condition, '?')
101 if 'rain' in parsed_json:
102 if '3h' in parsed_json['rain']:
103 p += float(parsed_json['rain']['3h'])
104 elif '1h' in parsed_json['rain']:
105 p += float(parsed_json['rain']['1h'])
106 if 'snow' in parsed_json:
107 if '3h' in parsed_json['snow']:
108 p += float(parsed_json['snow']['3h'])
109 elif '1h' in parsed_json['snow']:
110 p += float(parsed_json['snow']['1h'])
111 if dt == now.date() and now.hour > 18 and condition == 'Clear':
113 self.weather_data[dt] = WeatherData(
115 high=float(parsed_json["main"]["temp_max"]),
116 low=float(parsed_json["main"]["temp_min"]),
117 precipitation_inches=p / 25.4,
118 conditions=[condition],
119 most_common_condition=condition,
123 www = urllib.request.urlopen(
124 f"http://api.openweathermap.org/data/2.5/forecast?{param}&APPID={key}&units=imperial"
126 response = www.read()
128 parsed_json = json.loads(response)
129 logger.debug(parsed_json)
130 count = parsed_json["cnt"]
131 for x in range(count):
132 data = parsed_json["list"][x]
133 dt = datetime.datetime.strptime(data['dt_txt'], '%Y-%m-%d %H:%M:%S')
141 data["main"]["temp"],
142 data['main']['temp_min'],
143 data['main']['temp_max'],
145 if highs[dt] is None or temp > highs[dt]:
147 if lows[dt] is None or temp < lows[dt]:
149 cond = data["weather"][0]["main"]
151 if 'rain' in parsed_json:
152 if '3h' in parsed_json['rain']:
153 precip[dt] += float(parsed_json['rain']['3h'])
154 elif '1h' in parsed_json['rain']:
155 precip[dt] += float(parsed_json['rain']['1h'])
156 if 'snow' in parsed_json:
157 if '3h' in parsed_json['snow']:
158 precip[dt] += float(parsed_json['snow']['3h'])
159 elif '1h' in parsed_json['snow']:
160 precip[dt] += float(parsed_json['snow']['1h'])
161 conditions[dt].append(cond)
163 today = datetime_utils.now_pacific().date()
164 for dt in sorted(dates):
166 high = highs.get(dt, None)
167 if high is not None and self.weather_data[today].high < high:
168 self.weather_data[today].high = high
170 most_common_condition = list_utils.most_common(conditions[dt])
171 icon = icon_by_condition.get(most_common_condition, '?')
172 if dt == now.date() and now.hour > 18 and condition == 'Clear':
174 self.weather_data[dt] = WeatherData(
178 precipitation_inches=precip[dt] / 25.4,
179 conditions=conditions[dt],
180 most_common_condition=most_common_condition,
186 def load(cls) -> Any:
187 if persistent.was_file_written_within_n_seconds(
188 config.config['weather_data_cachefile'],
189 config.config['weather_data_stalest_acceptable'].total_seconds(),
193 with open(config.config['weather_data_cachefile'], 'rb') as rf:
194 weather_data = pickle.load(rf)
195 return cls(weather_data)
199 def save(self) -> bool:
202 with open(config.config['weather_data_cachefile'], 'wb') as wf:
206 pickle.HIGHEST_PROTOCOL,