[Digi-Key Follow Me Issue 2] Task 4: Calendar & Clock
[Copy link]
Subtask 1: Calendar & Clock - Complete a perpetual calendar clock that can be updated via the Internet and display local weather information
Recommended device: Adafruit ESP32-S3 TFT Feather
The official website has a good reference example
https://learn.adafruit.com/mini-weather-station-esp32-s2-tft
Free weather service
https://www.sojson.com/api/weather.html
Use the http get request library function to get the weather data in json format, parse it and display it on the screen
import time
import board
import ssl
import wifi
import socketpool
import adafruit_requests
from adafruit_display_text import label, wrap_text_to_lines
from adafruit_bitmap_font import bitmap_font
color = 0xF01414
font = bitmap_font.load_font("wenquanyi_13px.pcf")
display = board.DISPLAY
display.brightness = 0.25
display.rotation = 0
JSON_TIME_URL = "http://quan.suning.com/getSysTime.do"
JSON_weather_URL = "http://t.weather.sojson.com/api/weather/city/{}"
pool = socketpool.SocketPool(wifi.radio)
requests = adafruit_requests.Session(pool, ssl.create_default_context())
def refresh_screen(print_text):
text_area = label.Label(font, text=print_text, scale=1)
text_area.x = 2
text_area.y = 10
text_area.scale = 1
text_area.color = color
display.show(text_area)
def get_data():
try:
response = requests.get(JSON_TIME_URL)
except ConnectionError as e:
print("Connection Error:", e)
print("Retrying in 60 seconds")
time_data = response.json()['sysTime2'][:-3]
try:
city_code = "101200101"
url = JSON_weather_URL.format(city_code)
response = requests.get(url)
except ConnectionError as e:
print("connect error:{},retry in 60s".format(e))
weather_data = response.json()
cityInfo = weather_data['cityInfo']
city_weather = weather_data['data']
forecast = city_weather['forecast']
dis_str = ""+cityInfo['parent']+' '+cityInfo['city']
dis_str += " "+time_data
dis_str += "\n" + forecast[0]['week']
dis_str += ' 空气质量:' + city_weather['quality']
dis_str += "\n温度:"+city_weather['wendu']+"℃"
dis_str += " 湿度:" + city_weather['shidu']
dis_str += "\n明天最"+forecast[1]['high']+' 最'+forecast[1]['low']
return dis_str
while not wifi.radio.ipv4_address:
try:
wifi.radio.connect(os.getenv('CIRCUITPY_WIFI_SSID'), os.getenv('CIRCUITPY_WIFI_PASSWORD'))
except ConnectionError as e:
print("connecti error:{},retry in 2s".format(e))
time.sleep(2)
print("get ip:", wifi.radio.ipv4_address)
while True:
info = get_data()
refresh_screen(info)
time.sleep(60)
Effect:
|