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)