【得捷电子Follow me第2期】+任务4:天气和时间
[复制链接]
主要分为这几步
然后代码中有:
city_code = "101020100"
url = JSON_weather_URL.format(city_code)
这里使用了北京市的城市代码"101020100"。
城市代码是一个唯一标识每个城市的编号。不同天气API可能有不同的城市代码系统。
这个天气API文档中给出了常见城市及其代码:
- 北京:101010100
- 上海:101020100
- 广州:101280601
所以通过传入正确的城市代码,就可以从API获取对应城市的天气数据。
这样设计可以支持获取全球任意城市天气,只需要知道对应的城市代码即可。
代码
import board, os, wifi
import time
import ssl
import socketpool
import adafruit_requests
from adafruit_display_text import label, wrap_text_to_lines
from adafruit_bitmap_font import bitmap_font
color = 0xFFFFFF
font = bitmap_font.load_font("fonts\wenquanyi_10pt.pcf")
display = board.DISPLAY
display.brightness = 1
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 screen(print_text):
text_area = label.Label(font, text=print_text, scale=1)
text_area.x = 5
text_area.y = 15
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 = "101020100"
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['city'] + ' ' + forecast[0]['week']
dis_str += "\n时间:"+time_data
dis_str += '\n空气质量:' + city_weather['quality']
dis_str += "\n温度:"+city_weather['wendu']+"℃"
dis_str += "\n湿度:" + city_weather['shidu']
return dis_str
while not wifi.radio.ipv4_address:
try:
wifi.radio.connect('ZZ', '12138888')
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()
screen(info)
time.sleep(60)
|