Skip to content

Commit cc5cbcc

Browse files
committed
openmeteo magtag weather update
1 parent 4d0a717 commit cc5cbcc

File tree

4 files changed

+319
-0
lines changed

4 files changed

+319
-0
lines changed
5.13 KB
Binary file not shown.
2.01 KB
Binary file not shown.
22.3 KB
Binary file not shown.
Lines changed: 319 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,319 @@
1+
# SPDX-FileCopyrightText: 2024 Carter Nelson for Adafruit Industries
2+
#
3+
# SPDX-License-Identifier: MIT
4+
# pylint: disable=redefined-outer-name, eval-used, wrong-import-order
5+
6+
import time
7+
import terminalio
8+
import displayio
9+
import adafruit_imageload
10+
from adafruit_display_text import label
11+
from adafruit_magtag.magtag import MagTag
12+
# needed for NTP
13+
import wifi
14+
import socketpool
15+
import adafruit_ntp
16+
17+
# --| USER CONFIG |--------------------------
18+
LAT = 47.6 # latitude
19+
LON = -122.3 # longitude
20+
TMZ = "America/Los_Angeles" # https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
21+
METRIC = False # set to True for metric units
22+
# -------------------------------------------
23+
24+
# ----------------------------
25+
# Define various assets
26+
# ----------------------------
27+
BACKGROUND_BMP = "/bmps/weather_bg.bmp"
28+
ICONS_LARGE_FILE = "/bmps/weather_icons_70px.bmp"
29+
ICONS_SMALL_FILE = "/bmps/weather_icons_20px.bmp"
30+
DAYS = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")
31+
MONTHS = (
32+
"January",
33+
"February",
34+
"March",
35+
"April",
36+
"May",
37+
"June",
38+
"July",
39+
"August",
40+
"September",
41+
"October",
42+
"November",
43+
"December",
44+
)
45+
46+
# Weather Code Information from https://open-meteo.com/en/docs
47+
# Code Description
48+
# 0 Clear sky
49+
# 1, 2, 3 Mainly clear, partly cloudy, and overcast
50+
# 45, 48 Fog and depositing rime fog
51+
# 51, 53, 55 Drizzle: Light, moderate, and dense intensity
52+
# 56, 57 Freezing Drizzle: Light and dense intensity
53+
# 61, 63, 65 Rain: Slight, moderate and heavy intensity
54+
# 66, 67 Freezing Rain: Light and heavy intensity
55+
# 71, 73, 75 Snow fall: Slight, moderate, and heavy intensity
56+
# 77 Snow grains
57+
# 80, 81, 82 Rain showers: Slight, moderate, and violent
58+
# 85, 86 Snow showers slight and heavy
59+
# 95 * Thunderstorm: Slight or moderate
60+
# 96, 99 * Thunderstorm with slight and heavy hail
61+
62+
# Map the above WMO codes to index of icon in 3x3 spritesheet
63+
WMO_CODE_TO_ICON = (
64+
(0,), # 0 = sunny
65+
(1,), # 1 = partly sunny/cloudy
66+
(2,), # 2 = cloudy
67+
(3,), # 3 = very cloudy
68+
(61, 63, 65), # 4 = rain
69+
(51, 53, 55, 80, 81, 82), # 5 = showers
70+
(95, 96, 99), # 6 = storms
71+
(56, 57, 66, 67, 71, 73, 75, 77, 85, 86), # 7 = snow
72+
(45, 48), # 8 = fog and stuff
73+
)
74+
75+
magtag = MagTag()
76+
77+
# ----------------------------
78+
# Backgrounnd bitmap
79+
# ----------------------------
80+
magtag.graphics.set_background(BACKGROUND_BMP)
81+
82+
# ----------------------------
83+
# Weather icons sprite sheet
84+
# ----------------------------
85+
icons_large_bmp, icons_large_pal = adafruit_imageload.load(ICONS_LARGE_FILE)
86+
icons_small_bmp, icons_small_pal = adafruit_imageload.load(ICONS_SMALL_FILE)
87+
88+
# /////////////////////////////////////////////////////////////////////////
89+
# helper functions
90+
91+
def get_forecast():
92+
URL = f"https://api.open-meteo.com/v1/forecast?latitude={LAT}&longitude={LON}&"
93+
URL += "daily=weather_code,temperature_2m_max,temperature_2m_min,sunrise,sunset,wind_speed_10m_max,wind_direction_10m_dominant"
94+
URL += "&timeformat=unixtime"
95+
URL += f"&timezone={TMZ}"
96+
resp = magtag.network.fetch(URL)
97+
return resp.json()
98+
99+
100+
def make_banner(x=0, y=0):
101+
"""Make a single future forecast info banner group."""
102+
day_of_week = label.Label(terminalio.FONT, text="DAY", color=0x000000)
103+
day_of_week.anchor_point = (0, 0.5)
104+
day_of_week.anchored_position = (0, 10)
105+
106+
icon = displayio.TileGrid(
107+
icons_small_bmp,
108+
pixel_shader=icons_small_pal,
109+
x=25,
110+
y=0,
111+
width=1,
112+
height=1,
113+
tile_width=20,
114+
tile_height=20,
115+
)
116+
117+
day_temp = label.Label(terminalio.FONT, text="+100F", color=0x000000)
118+
day_temp.anchor_point = (0, 0.5)
119+
day_temp.anchored_position = (50, 10)
120+
121+
group = displayio.Group(x=x, y=y)
122+
group.append(day_of_week)
123+
group.append(icon)
124+
group.append(day_temp)
125+
126+
return group
127+
128+
129+
def temperature_text(tempC):
130+
if METRIC:
131+
return "{:3.0f}C".format(tempC)
132+
else:
133+
return "{:3.0f}F".format(32.0 + 1.8 * tempC)
134+
135+
136+
def wind_text(speedkmh, direction):
137+
wind_dir = "N"
138+
if direction < 337:
139+
wind_dir = "NW"
140+
if direction < 293:
141+
wind_dir = "W"
142+
if direction < 247:
143+
wind_dir = "SW"
144+
if direction < 202:
145+
wind_dir = "S"
146+
if direction < 157:
147+
wind_dir = "SE"
148+
if direction < 112:
149+
wind_dir = "E"
150+
if direction < 67:
151+
wind_dir = "NE"
152+
if direction < 22:
153+
wind_dir = "N"
154+
155+
wtext = f"from {wind_dir} "
156+
157+
if METRIC:
158+
wtext += "{:2.0f}kmh".format(speedkmh)
159+
else:
160+
wtext += "{:2.0f}mph".format(0.621371 * speedkmh)
161+
162+
return wtext
163+
164+
165+
def update_today(data):
166+
"""Update today weather info."""
167+
# date text
168+
s = data["daily"]["time"][0] + data["utc_offset_seconds"]
169+
t = time.localtime(s)
170+
today_date.text = "{} {} {}, {}".format(
171+
DAYS[t.tm_wday].upper(),
172+
MONTHS[t.tm_mon - 1].upper(),
173+
t.tm_mday,
174+
t.tm_year
175+
)
176+
# weather icon
177+
w = data["daily"]["weather_code"][0]
178+
today_icon[0] = next(i for i, t in enumerate(WMO_CODE_TO_ICON) if w in t)
179+
# temperatures
180+
today_low_temp.text = temperature_text(data["daily"]["temperature_2m_min"][0])
181+
today_high_temp.text = temperature_text(data["daily"]["temperature_2m_max"][0])
182+
# wind
183+
s = data["daily"]["wind_speed_10m_max"][0]
184+
d = data["daily"]["wind_direction_10m_dominant"][0]
185+
today_wind.text = wind_text(s, d)
186+
# sunrise/set
187+
sr = time.localtime(data["daily"]["sunrise"][0] + data["utc_offset_seconds"])
188+
ss = time.localtime(data["daily"]["sunset"][0] + data["utc_offset_seconds"])
189+
today_sunrise.text = "{:2d}:{:02d} AM".format(sr.tm_hour, sr.tm_min)
190+
today_sunset.text = "{:2d}:{:02d} PM".format(ss.tm_hour - 12, ss.tm_min)
191+
192+
193+
def update_future(data):
194+
"""Update the future forecast info."""
195+
for i, banner in enumerate(future_banners):
196+
# day of week
197+
s = data["daily"]["time"][i+1] + data["utc_offset_seconds"]
198+
t = time.localtime(s)
199+
banner[0].text = DAYS[t.tm_wday][:3].upper()
200+
# weather icon
201+
w = data["daily"]["weather_code"][i+1]
202+
banner[1][0] = next(x for x, t in enumerate(WMO_CODE_TO_ICON) if w in t)
203+
# temperature
204+
t = data["daily"]["temperature_2m_max"][i+1]
205+
banner[2].text = temperature_text(t)
206+
207+
208+
def get_ntp_time(offset):
209+
"""Use NTP to get current local time."""
210+
pool = socketpool.SocketPool(wifi.radio)
211+
ntp = adafruit_ntp.NTP(pool, tz_offset=offset)
212+
if ntp:
213+
return ntp.datetime
214+
else:
215+
return None
216+
217+
218+
def go_to_sleep(current_time):
219+
"""Enter deep sleep for time needed."""
220+
# compute current time offset in seconds
221+
hour = current_time.tm_hour
222+
minutes = current_time.tm_min
223+
seconds = current_time.tm_sec
224+
seconds_since_midnight = 60 * (hour * 60 + minutes) + seconds
225+
three_fifteen = (3 * 60 + 15) * 60
226+
# wake up 15 minutes after 3am
227+
seconds_to_sleep = (24 * 60 * 60 - seconds_since_midnight) + three_fifteen
228+
print(
229+
"Sleeping for {} hours, {} minutes".format(
230+
seconds_to_sleep // 3600, (seconds_to_sleep // 60) % 60
231+
)
232+
)
233+
magtag.exit_and_deep_sleep(seconds_to_sleep)
234+
235+
236+
# ===========
237+
# U I
238+
# ===========
239+
today_date = label.Label(terminalio.FONT, text="?" * 30, color=0x000000)
240+
today_date.anchor_point = (0, 0)
241+
today_date.anchored_position = (15, 14)
242+
243+
location_name = label.Label(terminalio.FONT, text=f"({LAT},{LON})", color=0x000000)
244+
location_name.anchor_point = (0, 0)
245+
location_name.anchored_position = (15, 25)
246+
247+
today_icon = displayio.TileGrid(
248+
icons_large_bmp,
249+
pixel_shader=icons_small_pal,
250+
x=10,
251+
y=40,
252+
width=1,
253+
height=1,
254+
tile_width=70,
255+
tile_height=70,
256+
)
257+
258+
today_low_temp = label.Label(terminalio.FONT, text="+100F", color=0x000000)
259+
today_low_temp.anchor_point = (0.5, 0)
260+
today_low_temp.anchored_position = (122, 60)
261+
262+
today_high_temp = label.Label(terminalio.FONT, text="+100F", color=0x000000)
263+
today_high_temp.anchor_point = (0.5, 0)
264+
today_high_temp.anchored_position = (162, 60)
265+
266+
today_wind = label.Label(terminalio.FONT, text="99m/s", color=0x000000)
267+
today_wind.anchor_point = (0, 0.5)
268+
today_wind.anchored_position = (110, 95)
269+
270+
today_sunrise = label.Label(terminalio.FONT, text="12:12 PM", color=0x000000)
271+
today_sunrise.anchor_point = (0, 0.5)
272+
today_sunrise.anchored_position = (45, 117)
273+
274+
today_sunset = label.Label(terminalio.FONT, text="12:12 PM", color=0x000000)
275+
today_sunset.anchor_point = (0, 0.5)
276+
today_sunset.anchored_position = (130, 117)
277+
278+
today_banner = displayio.Group()
279+
today_banner.append(today_date)
280+
today_banner.append(location_name)
281+
today_banner.append(today_icon)
282+
today_banner.append(today_low_temp)
283+
today_banner.append(today_high_temp)
284+
today_banner.append(today_wind)
285+
today_banner.append(today_sunrise)
286+
today_banner.append(today_sunset)
287+
288+
future_banners = [
289+
make_banner(x=210, y=18),
290+
make_banner(x=210, y=39),
291+
make_banner(x=210, y=60),
292+
make_banner(x=210, y=81),
293+
make_banner(x=210, y=102),
294+
]
295+
296+
magtag.splash.append(today_banner)
297+
for future_banner in future_banners:
298+
magtag.splash.append(future_banner)
299+
300+
# ===========
301+
# M A I N
302+
# ===========
303+
print("Fetching forecast...")
304+
forecast_data = get_forecast()
305+
306+
print("Updating...")
307+
update_today(forecast_data)
308+
update_future(forecast_data)
309+
310+
print("Refreshing...")
311+
time.sleep(magtag.display.time_to_refresh + 1)
312+
magtag.display.refresh()
313+
time.sleep(magtag.display.time_to_refresh + 1)
314+
315+
print("Sleeping...")
316+
go_to_sleep(get_ntp_time(forecast_data["utc_offset_seconds"]/3600))
317+
# entire code will run again after deep sleep cycle
318+
# similar to hitting the reset button
319+

0 commit comments

Comments
 (0)