Created
June 12, 2023 04:11
-
-
Save tmountjr/ee12fe9d5e498906dc42cbd49354a25e to your computer and use it in GitHub Desktop.
CircuitPython AQI Meter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import ssl | |
import time | |
import wifi | |
import board | |
from neopixel import NeoPixel | |
from socketpool import SocketPool | |
from adafruit_requests import Session | |
print(f'IP address: {wifi.radio.ipv4_address}') | |
num_pixels = 8 | |
pixels = NeoPixel(board.GP0, num_pixels, brightness=0.05, auto_write=False) | |
# Make sure your settings.toml file has ZIP and WEATHER_KEY defined. | |
# Get an API key for airnow.gov here: https://docs.airnowapi.org/account/request/ | |
url = f'https://www.airnowapi.org/aq/observation/zipCode/current/?format=application/json&zipCode={os.getenv("ZIP")}&distance=5&API_KEY={os.getenv("WEATHER_KEY")}' | |
pool = SocketPool(wifi.radio) | |
requests = Session(pool, ssl.create_default_context()) | |
def show_aqi(): | |
""" | |
Get Air Quality Index information from airnow.gov and set the neopixel stick according to the PM2.5 value. | |
""" | |
aq_data = requests.get(url).json() | |
pm25 = next(item for item in aq_data if item['ParameterName'] == 'PM2.5') | |
aqi = pm25['AQI'] | |
print(f'Current AQI: {aqi}') | |
if (aqi >= 0): | |
pixels[0] = (0, 255, 0) | |
if (aqi >= 50): | |
pixels[1] = (150, 150, 0) | |
if (aqi >= 100): | |
pixels[2] = (215, 255, 5) | |
if (aqi >= 150): | |
pixels[3] = (255, 0, 0) | |
if (aqi >= 200): | |
pixels[4] = (180, 0, 255) | |
if (aqi >= 250): | |
pixels[5] = (180, 0, 255) | |
if (aqi >= 300): | |
pixels[6] = (0, 0, 255) | |
pixels[7] = (0, 0, 255) | |
pixels.show() | |
# Initialize on boot | |
show_aqi() | |
now = time.mktime(time.localtime()) | |
update_interval = 60 * 60 # 1h since apparently this system doesn't get frequent updates. | |
next_update = now + update_interval | |
while True: | |
current_time = time.mktime(time.localtime()) | |
if current_time >= next_update: | |
print(f'Updating AQI data...') | |
show_aqi() | |
next_update = current_time + update_interval |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment