-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcode.py
310 lines (261 loc) · 9.76 KB
/
code.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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
import time
import terminalio
import displayio
import adafruit_imageload
import board
import busio
import supervisor
import adafruit_scd4x
from adafruit_display_text import label
from adafruit_magtag.magtag import MagTag
from adafruit_pm25.i2c import PM25_I2C
from secrets import secrets
# --| USER CONFIG |--------------------------
METRIC = True # set to True for metric units
# -------------------------------------------
# ----------------------------
# Define various assets
# ----------------------------
BACKGROUND_BMP = "/bmps/weather_bg.bmp"
ICONS_LARGE_FILE = "/bmps/weather_icons_70px.bmp"
ICONS_SMALL_FILE = "/bmps/weather_icons_20px.bmp"
ICON_MAP = ("01", "02", "03", "04", "09", "10", "11", "13", "50")
DAYS = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")
MONTHS = (
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
)
magtag = MagTag()
# ----------------------------
# Backgrounnd bitmap
# ----------------------------
magtag.graphics.set_background(BACKGROUND_BMP)
# ----------------------------
# Weather icons sprite sheet
# ----------------------------
icons_large_bmp, icons_large_pal = adafruit_imageload.load(ICONS_LARGE_FILE)
icons_small_bmp, icons_small_pal = adafruit_imageload.load(ICONS_SMALL_FILE)
# /////////////////////////////////////////////////////////////////////////
def get_data_source_url(api="onecall", location=None):
"""Build and return the URL for the OpenWeather API."""
if api.upper() == "FORECAST5":
URL = "https://api.openweathermap.org/data/2.5/forecast?"
URL += "q=" + location
elif api.upper() == "ONECALL":
URL = "https://api.openweathermap.org/data/2.5/onecall?exclude=minutely,hourly,alerts"
URL += "&lat={}".format(location[0])
URL += "&lon={}".format(location[1])
else:
raise ValueError("Unknown API type: " + api)
return URL + "&appid=" + secrets["openweather_token"]
def get_latlon():
"""Use the Forecast5 API to determine lat/lon for given city."""
magtag.url = get_data_source_url(api="forecast5", location=secrets["openweather_location"])
magtag.json_path = ["city"]
raw_data = magtag.fetch()
return raw_data["coord"]["lat"], raw_data["coord"]["lon"]
def get_forecast(location):
"""Use OneCall API to fetch forecast and timezone data."""
resp = magtag.network.fetch(get_data_source_url(api="onecall", location=location))
json_data = resp.json()
return json_data["daily"], json_data["current"]["dt"], json_data["timezone_offset"]
def make_banner(x=0, y=0):
"""Make a single measurement info banner group."""
mes = label.Label(terminalio.FONT, text="MES", color=0x000000)
mes.anchor_point = (0, 0.5)
mes.anchored_position = (0, 10)
val = label.Label(terminalio.FONT, text="+100F", color=0x000000)
val.anchor_point = (0, 0.5)
val.anchored_position = (30, 10)
group = displayio.Group(x=x, y=y)
group.append(mes)
group.append(val)
return group
def temperature_text(tempK):
if METRIC:
return "{:3.0f}C".format(tempK - 273.15)
else:
return "{:3.0f}F".format(32.0 + 1.8 * (tempK - 273.15))
def wind_text(speedms):
if METRIC:
return "{:3.0f}m/s".format(speedms)
else:
return "{:3.0f}mph".format(2.23694 * speedms)
def update_banner(banner, data):
"""Update supplied forecast banner with supplied data."""
banner[0].text = data["mes"]
banner[1].text = data["val"]
def update_today(data, tz_offset=0):
"""Update today info banner."""
date = time.localtime(data["dt"])
sunrise = time.localtime(data["sunrise"] + tz_offset)
sunset = time.localtime(data["sunset"] + tz_offset)
today_date.text = "{} {} {}, {}".format(
DAYS[date.tm_wday].upper(),
MONTHS[date.tm_mon - 1].upper(),
date.tm_mday,
date.tm_year,
)
today_icon[0] = ICON_MAP.index(data["weather"][0]["icon"][:2])
today_morn_temp.text = temperature_text(data["temp"]["morn"])
today_day_temp.text = temperature_text(data["temp"]["day"])
today_night_temp.text = temperature_text(data["temp"]["night"])
today_humidity.text = "{:3d}%".format(data["humidity"])
today_wind.text = wind_text(data["wind_speed"])
today_sunrise.text = "{:2d}:{:02d} AM".format(sunrise.tm_hour, sunrise.tm_min)
today_sunset.text = "{:2d}:{:02d} PM".format(sunset.tm_hour - 12, sunset.tm_min)
# ===========
# U I
# ===========
today_date = label.Label(terminalio.FONT, text="?" * 30, color=0x000000)
today_date.anchor_point = (0, 0)
today_date.anchored_position = (15, 13)
city_name = label.Label(
terminalio.FONT, text=secrets["openweather_location"], color=0x000000
)
city_name.anchor_point = (0, 0)
city_name.anchored_position = (15, 24)
today_icon = displayio.TileGrid(
icons_large_bmp,
pixel_shader=icons_small_pal,
x=10,
y=40,
width=1,
height=1,
tile_width=70,
tile_height=70,
)
today_morn_temp = label.Label(terminalio.FONT, text="+100F", color=0x000000)
today_morn_temp.anchor_point = (0.5, 0)
today_morn_temp.anchored_position = (118, 59)
today_day_temp = label.Label(terminalio.FONT, text="+100F", color=0x000000)
today_day_temp.anchor_point = (0.5, 0)
today_day_temp.anchored_position = (149, 59)
today_night_temp = label.Label(terminalio.FONT, text="+100F", color=0x000000)
today_night_temp.anchor_point = (0.5, 0)
today_night_temp.anchored_position = (180, 59)
today_humidity = label.Label(terminalio.FONT, text="100%", color=0x000000)
today_humidity.anchor_point = (0, 0.5)
today_humidity.anchored_position = (105, 95)
today_wind = label.Label(terminalio.FONT, text="99m/s", color=0x000000)
today_wind.anchor_point = (0, 0.5)
today_wind.anchored_position = (155, 95)
today_sunrise = label.Label(terminalio.FONT, text="12:12 PM", color=0x000000)
today_sunrise.anchor_point = (0, 0.5)
today_sunrise.anchored_position = (45, 117)
today_sunset = label.Label(terminalio.FONT, text="12:12 PM", color=0x000000)
today_sunset.anchor_point = (0, 0.5)
today_sunset.anchored_position = (130, 117)
today_banner = displayio.Group()
today_banner.append(today_date)
today_banner.append(city_name)
today_banner.append(today_icon)
today_banner.append(today_morn_temp)
today_banner.append(today_day_temp)
today_banner.append(today_night_temp)
today_banner.append(today_humidity)
today_banner.append(today_wind)
today_banner.append(today_sunrise)
today_banner.append(today_sunset)
mes_banners = [
make_banner(x=210, y=18),
make_banner(x=210, y=39),
make_banner(x=210, y=60),
make_banner(x=210, y=81),
make_banner(x=210, y=102),
]
magtag.splash.append(today_banner)
for future_banner in mes_banners:
magtag.splash.append(future_banner)
# ===========
# M A I N
# ===========
supervisor.disable_autoreload() # Kept reloading on Win10?
i2c = busio.I2C(board.SCL, board.SDA, frequency=100000)
scd4x = adafruit_scd4x.SCD4X(i2c)
pm25 = PM25_I2C(i2c, None)
print("SCD4x Serial number:", [hex(i) for i in scd4x.serial_number])
time.sleep(2)
scd4x.start_periodic_measurement()
print("Waiting for first measurement....")
print("Getting Lat/Lon...")
latlon = get_latlon()
print(secrets["openweather_location"])
print(latlon)
while True:
# Initialize here so acquisition during loop result in an obvious failure
tmp = "ERR"
hum = "ERR"
co2 = "ERR"
pmdata = {
"pm10 env": -1,
"pm25 env": -1,
}
if scd4x.data_ready:
print("CO2: %d ppm" % scd4x.CO2)
print("Temperature: %0.1f *C" % scd4x.temperature)
print("Humidity: %0.1f %%" % scd4x.relative_humidity)
co2 = "%d ppm" % scd4x.CO2
if METRIC:
tmp = "%0.1f *C" % scd4x.temperature
else:
tmp = "%0.1f *F" % (scd4x.temperature * 9/5 + 32)
hum = "%0.1f %%" % scd4x.relative_humidity
print()
else:
continue
try:
aqdata = pm25.read()
# print(aqdata)
pmdata = aqdata
except RuntimeError:
print("Unable to read from sensor, retrying...")
continue
print()
print("Concentration Units (standard)")
print("---------------------------------------")
print(
"PM 1.0: %d\tPM2.5: %d\tPM10: %d"
% (aqdata["pm10 standard"], aqdata["pm25 standard"], aqdata["pm100 standard"])
)
print("Concentration Units (environmental)")
print("---------------------------------------")
print(
"PM 1.0: %d\tPM2.5: %d\tPM10: %d"
% (aqdata["pm10 env"], aqdata["pm25 env"], aqdata["pm100 env"])
)
print("---------------------------------------")
print("Particles > 0.3um / 0.1L air:", aqdata["particles 03um"])
print("Particles > 0.5um / 0.1L air:", aqdata["particles 05um"])
print("Particles > 1.0um / 0.1L air:", aqdata["particles 10um"])
print("Particles > 2.5um / 0.1L air:", aqdata["particles 25um"])
print("Particles > 5.0um / 0.1L air:", aqdata["particles 50um"])
print("Particles > 10 um / 0.1L air:", aqdata["particles 100um"])
print("---------------------------------------")
#time.sleep(1)
print("Fetching forecast...")
forecast_data, utc_time, local_tz_offset = get_forecast(latlon)
print("Updating...")
update_today(forecast_data[0], local_tz_offset)
# We have space for 5 banners
update_banner(mes_banners[0], {"mes": "Temp", "val": tmp})
update_banner(mes_banners[1], {"mes": "Hum", "val": hum})
update_banner(mes_banners[2], {"mes": "CO2", "val": co2})
update_banner(mes_banners[3], {"mes": "PM1.0", "val": " %d ppm" % pmdata["pm10 env"]})
update_banner(mes_banners[4], {"mes": "PM2.5", "val": " %d ppm" % pmdata["pm25 env"]})
print("Refreshing...")
time.sleep(magtag.display.time_to_refresh + 1)
magtag.display.refresh()
time.sleep(magtag.display.time_to_refresh + 1)
print("Sleeping...")
time.sleep(60)