import usocket as socket
import utime
import ujson
import wlan
try:
import ussl as ssl
except:
import ssl
RECONNECT_INTERVAL = 20000 # millisecond
# === CWB API 設定 ===
host = "opendata.cwa.gov.tw" # 伺服器網址,不可動
port = 443 # https
API_KEY_CWB = "CWB-" # "你的CWB授權碼"
LOCATION_CWB = "臺北市"
# === 取得 API JSON ===
def get_api_json(url):
request = "GET {} HTTP/1.0\r\nHost: {}\r\n\r\n".format(url, host)
try:
addr = socket.getaddrinfo(host, port)[0][-1] # 取得連線到伺服器的相關訊息
Socket1 = socket.socket()
Socket1.connect(addr) # 與伺服器進行連線
ssl_sock = ssl.wrap_socket(Socket1) # SSL wrap
ssl_sock.write(request.encode()) # send data
# 讀取回應
response = b""
while True:
data = ssl_sock.read(1024)
if not data:
break
response += data
ssl_sock.close()
# 解析 HTTP header 與 JSON
response = response.decode()
json_start = response.find("{")
json_data = response[json_start:]
return ujson.loads(json_data)
except Exception as e:
print("讀取失敗:", e)
return None
# === 解析並顯示天氣資訊 ===
def print_weather(data):
if not data:
print("沒有資料可顯示")
return
location = data["records"]["location"][0]
city = location["locationName"]
print("地區:", city)
for elem in location["weatherElement"]:
element_name = elem["elementName"]
description = elem["time"][0]["parameter"]["parameterName"]
print(f"{element_name}: {description}")
# Start Function
if __name__ == '__main__':
wlan.connect_wifi() # Connecting to WiFi Router
lastTime = utime.ticks_ms()
while True:
try:
currTime = utime.ticks_ms()
if (currTime - lastTime > RECONNECT_INTERVAL):
lastTime = currTime
print("----------------------")
path = "/api/v1/rest/datastore/F-C0032-001?Authorization={}&locationName={}".format(API_KEY_CWB, LOCATION_CWB)
data = get_api_json(path)
print_weather(data)
# Do other tasks while waiting for button press
utime.sleep_ms(100)
except Exception as e:
print(e)
except KeyboardInterrupt: # 使用者中斷執行(通常是輸入^C)
print("Stop")