import network
import usocket
import ussl
import ujson
import time
# === WiFi 設定 ===
WIFI_SSID = "Wokwi-GUEST" # WIFI_SSID = "你的WiFi帳號"
WIFI_PASS = "" # WIFI_PASS = "你的WiFi密碼"
# === CWB API 設定 ===
API_KEY = "CWB-7A602268-CB04-4170-8A8D-0DBC7A57312D" # "你的CWB授權碼"
LOCATION = "臺北市"
# === 連線 WiFi ===
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print("正在連接 WiFi...")
wlan.connect(WIFI_SSID, WIFI_PASS)
while not wlan.isconnected():
time.sleep(1)
print("等待連線中...")
print("已連上 WiFi:", wlan.ifconfig())
# === 取得 CWB JSON ===
def get_cwb_json(api_key, location):
host = "opendata.cwa.gov.tw"
port = 443
path = "/api/v1/rest/datastore/F-C0032-001?Authorization={}&locationName={}".format(api_key, location)
try:
# 建立 socket 連線
addr = usocket.getaddrinfo(host, port)[0][-1]
s = usocket.socket()
s.connect(addr)
s = ussl.wrap_socket(s)
# 發送 GET 請求
request = "GET {} HTTP/1.0\r\nHost: {}\r\n\r\n".format(path, host)
s.write(request.encode())
# 讀取回應
response = b""
while True:
data = s.read(1024)
if not data:
break
response += data
s.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}")
# === 主程式 ===
connect_wifi()
while True:
data = get_cwb_json(API_KEY, LOCATION)
print_weather(data)
print("----------------------")
time.sleep(600) # 每10分鐘更新一次