|
发表于 2025-6-16 09:04:22
|
显示全部楼层
本帖最后由 qilinchong 于 2025-6-16 09:21 编辑
我刚好做了一个,欢迎交流!
-- 配置区 --
local API_KEY = "" 此处替换你的心知KEY,免费注册使用
local LOCATION = "beijing"
local USE_HTTPS = false
-- 状态变量 --
local weather_data = {}
-- 英文到中文的映射表
local EN_TO_ZH_MAP = {
-- 天气状态映射
["Sunny"] = "晴",
["Cloudy"] = "多云",
["Overcast"] = "阴",
["Rain"] = "雨",
-- 城市名称映射
["Beijing"] = "北京",
-- 可以根据需要添加更多映射
}
-- 初始化函数 --
function on_init()
dofile("e_module.lua")
print("系统初始化完成")
-- 设置天气请求定时器(5秒后启动)
start_timer(1, 5000, 0, 0)
end
-- 增强版请求函数 --
function get_weather()
local url = string.format(
"%s://api.seniverse.com/v3/weather/now.json?key=%s&location=%s&language=en&unit=c",
USE_HTTPS and "https" or "http",
API_KEY,
LOCATION
)
if DEBUG_MODE then
print("\n[调试] 请求URL:", url:gsub(API_KEY, "******"))
print("设备时间:", os.date("%Y-%m-%d %H:%M:%S"))
end
http_request(1, url, 0, "Accept-Charset: utf-8", "")
end
-- 精准JSON解析 --
function parse_weather(json_str)
local data = {}
-- 基础字段匹配
data.city = json_str:match('"name":"([^"]+)"') or "N/A"
data.temp = json_str:match('"temperature":"?(%d+)%D*"?') or "N/A"
data.status = json_str:match('"text":"([^"]+)"') or "N/A"
-- 错误检测
data.error = json_str:match('"status":"([^"]+)"') -- API错误状态
if DEBUG_MODE then
print("\n[调试] 原始响应片段:", json_str:sub(1, 100).."...")
print("解析结果:", data.city, data.temp, data.status)
end
return data
end
-- 响应处理函数 --
function on_http_response(taskid, response)
if taskid == 1 then
if response then
weather_data = parse_weather(response)
show_weather()
else
print("\n[网络错误] 可能原因:")
print("1. 物理网络未连接")
print("2. DNS解析失败")
print("3. 防火墙拦截")
print("4. API服务器不可用")
-- 失败重试逻辑
if retry_count < 3 then
retry_count = retry_count + 1
start_timer(1, 5000, 0, 0)
print(string.format("将在5秒后重试(剩余次数%d)", 3 - retry_count))
end
end
end
end
-- 数据显示函数 --
function show_weather()
print("\n==== 实时天气 ====")
if weather_data.error then
print("[API错误]", weather_data.error)
if weather_data.error == "invalid_key" then
print("解决方案:")
print("1. 访问心知控制台检查密钥")
print("2. 联系技术支持")
end
else
local city = EN_TO_ZH_MAP[weather_data.city] or weather_data.city
local status = EN_TO_ZH_MAP[weather_data.status] or weather_data.status
print("城市:", city)
print("状态:", status)
print("温度:", weather_data.temp.."℃")
print("更新时间:", os.date("%H:%M"))
end
print("==================")
end
-- 定时器回调 --
function on_timer(timer_id)
if timer_id == 1 then
get_weather()
end
end |
|