esp8266 获取天气信息

esp8266连接本地wifi。作为web client get 天气信息。

天气网站链接如下:

https://api.thinkpage.cn/v3/weather/now.json?key=wcmquevztdy1jpca&location=tianjin&language=en&unit=c

返回数据如下:



{"results":[{"location":{"id":"WWGQDCW6TBW1","name":"Tianjin","country":"CN","path":"Tianjin,Tianjin,China","timezone":"Asia/Shanghai","timezone_offset":"+08:00"},"now":{"text":"Cloudy","code":"4","temperature":"3"},"last_update":"2018-03-15T20:20:00+08:00"}]}

每秒申请一次,并解析json。

全部代码如下:

-- init.lua


---------------------
-- wifi
---------------------


print('Setting up WIFI...')
wifi.setmode(wifi.STATION)
station_cfg={}
station_cfg.ssid="NodeMCU"
station_cfg.pwd="12345678"
station_cfg.save=true
wifi.sta.config(station_cfg)


tmr.alarm(0, 1000, tmr.ALARM_AUTO, function()
    if wifi.sta.getip() == nil then
        print('Waiting for IP ...')
    else
        print('IP is ' .. wifi.sta.getip())
    tmr.stop(0)
    end
end)






tmr.alarm(1, 1000, tmr.ALARM_AUTO, function()
    if wifi.sta.getip() ~= nil then
srv=net.createConnection(net.TCP,0) 
srv:on("receive", function(conn, pl) 
print(pl) 
--value = sjson.decode(pl)
i,j=string.find(pl, "{")
sjson_str=string.sub(pl, i)
--print(sjson_str)


local sjson = require("sjson");
local json = sjson.decode(sjson_str);  
print(" City: " ..json.results[1]["location"]["name"])
print(" Weather: " ..json.results[1]["now"]["text"])
print(" Temperature: " ..json.results[1]["now"]["temperature"] .." C\n")
end)
srv:on("connection", function(conn, pl)


conn:send("GET /v3/weather/now.json?key=ptgoijxvh94mo6de&location=tianjin&language=en&unit=c HTTP/1.1\r\nHost: api.seniverse.com\r\nConnection: keep-alive\r\nAccept: */*\r\n\r\n")
end)
srv:connect(80,"api.seniverse.com")
    end
end)













  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值