/ PyPortal_AirQuality / code.py
code.py
1 # SPDX-FileCopyrightText: 2019 Limor Fried for Adafruit Industries 2 # 3 # SPDX-License-Identifier: MIT 4 5 """ 6 This example will access the twitter follow button API, grab a number like 7 the number of followers... and display it on a screen! 8 if you can find something that spits out JSON data, we can display it 9 """ 10 import time 11 import board 12 from adafruit_pyportal import PyPortal 13 14 # Get wifi details and more from a secrets.py file 15 try: 16 from secrets import secrets 17 except ImportError: 18 print("WiFi secrets are kept in secrets.py, please add them there!") 19 raise 20 21 # Change this to your zip code, not all locations have AQI data. Check 22 # https://airnow.gov/ to see if there's data available! 23 LOCATION = "90210" 24 25 # Set up where we'll be fetching data from 26 DATA_SOURCE = "http://www.airnowapi.org/aq/forecast/zipCode/?format=application/json" 27 # You'll need to get a token from airnow.gov, looks like '4d36e978-e325-11cec1-08002be10318' 28 DATA_SOURCE += "&zipCode="+LOCATION+"&API_KEY="+secrets['airnow_token'] 29 DATA_LOCATION = [1, "AQI"] 30 31 # the current working directory (where this file is) 32 cwd = ("/"+__file__).rsplit('/', 1)[0] 33 # Initialize the pyportal object and let us know what data to fetch and where 34 # to display it 35 pyportal = PyPortal(url=DATA_SOURCE, 36 json_path=DATA_LOCATION, 37 status_neopixel=board.NEOPIXEL, 38 default_bg=0x000000, 39 text_font=cwd+"/fonts/Helvetica-Bold-100.bdf", 40 text_position=(90, 100), 41 text_color=0x000000, 42 caption_text="Air Quality Index for "+LOCATION, 43 caption_font=cwd+"/fonts/HelveticaNeue-24.bdf", 44 caption_position=(15, 220), 45 caption_color=0x000000,) 46 47 while True: 48 try: 49 value = pyportal.fetch() 50 print("Response is", value) 51 if 0 <= value <= 50: 52 pyportal.set_background(0x66bb6a) # good 53 if 51 <= value <= 100: 54 pyportal.set_background(0xffeb3b) # moderate 55 if 101 <= value <= 150: 56 pyportal.set_background(0xf39c12) # sensitive 57 if 151 <= value <= 200: 58 pyportal.set_background(0xff5722) # unhealthy 59 if 201 <= value <= 300: 60 pyportal.set_background(0x8e24aa) # very unhealthy 61 if 301 <= value <= 500: 62 pyportal.set_background(0xb71c1c ) # hazardous 63 64 except RuntimeError as e: 65 print("Some error occured, retrying! -", e) 66 67 time.sleep(10*60) # wait 10 minutes before getting again