-
Notifications
You must be signed in to change notification settings - Fork 0
/
WeatherScreen.py
164 lines (143 loc) · 6.47 KB
/
WeatherScreen.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
import os, sys
try:
sys.path.append('./inkyphat-mods/src')
import inky_mod as inky
except:
print('WARNING: inkyphat-mods not found. Cannot use fast screen updates.')
import inky
import requests
from PIL import Image, ImageDraw, ImageFont
import time
#TODO: show weather alerts for location (if any are in place)
def getsize(font, text):
_, _, right, bottom = font.getbbox(text)
return (right, bottom)
def wrap(quote, width, font):
words = quote.split(" ")
reflowed = ''
line_length = 0
for i in range(len(words)):
word = words[i] + " "
word_length = getsize(font, word)[0]
line_length += word_length
if line_length < width:
reflowed += word
else:
line_length = word_length
reflowed = reflowed[:-1] + "\n" + word
reflowed = reflowed.rstrip()
return reflowed
def get_retry(*args, **kwargs):
max_retries = kwargs['max_retries'] if 'max_retries' in kwargs.keys() else 5
r = requests.get(*args, **kwargs)
retries = 0
while r.status_code != 200:
if retries > max_retries:
raise Exception('Max retries exceeded.')
time.sleep(2 ** retries)
r = requests.get(*args, **kwargs)
retries += 1
return r
class WeatherScreen:
def __init__(self, location, headers):
self.location = location
self.headers = headers
self.forecast_endpoint = None
self.hourly_forecast_endpoint = None
self.weekly_forecast = None
self.hourly_forecast = None
self.periods = None
self.display = inky.InkyWHAT('red')
self.img = Image.new("P", self.display.resolution)
def get_endpoints(self):
r = get_retry(f'https://api.weather.gov/points/{self.location[0]},{self.location[1]}/', headers=self.headers)
# query lat, lon of desired forecast location, returns forecast endpoints at grid cells for for local NWS office's forecast model
properties = r.json()['properties']
forecast_endpoint = properties['forecast']
hourly_forecast_endpoint = properties['forecastGridData']
print(f"endpoints: {forecast_endpoint}, {hourly_forecast_endpoint}")
self.forecast_endpoint = forecast_endpoint
self.hourly_forecast_endpoint = hourly_forecast_endpoint
return forecast_endpoint, hourly_forecast_endpoint
def get_weekly_forecast(self):
"""Retrieve 7-day forecast from NWS API"""
print('Retrieving 7-day forecast')
if not self.forecast_endpoint:
raise IOError('No endpoints set. Run self.get_endpoints() first.')
r = get_retry(self.forecast_endpoint, headers=self.headers)
print(r.status_code)
forecast = r.json()
return forecast
def get_hourly_forecast(self):
"""Retrieve hourly forecast from NWS API"""
print('Retrieving hourly forecast')
if not self.hourly_forecast_endpoint:
raise IOError('No endpoints set. Run self.get_endpoints() first.')
r = get_retry(self.hourly_forecast_endpoint, headers=self.headers)
print(r.status_code)
forecast = r.json()
return forecast
def update_forecasts(self):
"""Get endpoints (in case changed) and update forecast attributes"""
self.get_endpoints()
self.weekly_forecast = self.get_weekly_forecast()
self.hourly_forecast = self.get_hourly_forecast()
self.periods = [self.weekly_forecast['properties']['periods'][i] for i in range(14)]
return
def get_nws_icon(self, icon_url, icon_size=127):
# get NWS icon
icon = Image.open(get_retry(icon_url.replace('medium', 'large'), stream=True).raw)
icon = icon.resize((icon_size, icon_size), resample=Image.Resampling.BICUBIC)
# convert icon to red/black/white color palette
pal_img = Image.new("P", (1, 1))
pal_img.putpalette((255, 255, 255, 0, 0, 0, 255, 0, 0) + (0, 0, 0) * 252)
icon = icon.convert("RGB").quantize(palette=pal_img)
return icon
def make_image(self, frame_i=0, hpad=5, vpad=5, h=15, large_font=17, small_font=14):
"""
hpad, vpad: horizontal and vertical padding
h: text height
"""
# initialize image and drawing/text display
self.img = Image.new("P", self.display.resolution)
draw = ImageDraw.Draw(self.img)
font = ImageFont.truetype("FreeSansBold", large_font)
small_font = ImageFont.truetype("FreeSansBold", small_font)
# add icons, short forecast for next 3 forecast periods
for i, period in enumerate(self.periods[:3]):
# place icon
icon_size = 127
icon = self.get_nws_icon(period['icon'], icon_size=icon_size)
self.img.paste(icon, (hpad * (i + 1) + icon.width * i, vpad + h))
# place period name
message = period['name']
draw.text((hpad * (i + 1) + icon.width * (i + 0.5), vpad), message, self.display.BLACK, font, anchor='mt')
# place short forecast
message = wrap(period['shortForecast'], icon_size, small_font)
# cut to two lines if longer
if len(message.split("\n")) > 2:
message = "\n".join(message.split("\n")[:2])
bbox = draw.textbbox((0, 0), message, small_font)
draw.text((hpad * (i + 1) - bbox[2]//2 + icon.width * (i + 0.5), vpad + h + icon.height), message, self.display.BLACK, small_font, align='center')
# place temp for high/low
message = f"{period['temperature']} °{period['temperatureUnit']}"
draw.text((hpad * (i + 1) + icon.width * (i + 0.5), 2 * vpad + 3 * h + icon.height), message, self.display.BLACK, font, anchor='mt')
# add text for detailed forecast
font = ImageFont.truetype("FreeSansBold", 16)
x, y = 5, 205
message = wrap(f"{self.periods[frame_i]['name']}: {self.periods[frame_i]['detailedForecast']}", self.display.width - 10, font)
draw.text((x, y), message, self.display.BLACK, font)
bbox = draw.textbbox((x, y), message, font)
y = bbox[-1]
return self.img
def update_screen(self, fast=True, *args, **kwargs):
# make image
self.make_image(*args, **kwargs)
# write to display and update
self.img.save('weather_image.png')
self.display.set_image(self.img)
if fast:
self.display.fast_show(style=self.display.BLACK)
else:
self.display.show() # busy_wait=False)
return