ESP 8266(devkit v2)上的 NodeMCU 0.9.6-dev:dofile() 脚本未连接到 TCP 服务器
NodeMCU 0.9.6-dev on ESP 8266 (devkit v2): while dofile() script is not connecting to TCP-server
如前所述,我编写了一个连接到天气 API 并打印出结果的脚本。
当我运行逐行通过解释器(ESPlorer "Send to ESP- and run "逐行“”)时,一切正常,但是当我通过dofile()
执行它时,它无法连接到网站并失败。
我很困惑,希望你们中的一些人能发现我忽略的错误。
代码如下:
data= ""
s= net.createConnection(net.TCP, 0)
s:on("receive", function(so, da) data= da end)
s:connect(80, "api.openweathermap.org")
s:send("GET /data/2.5/weather?q=berlin,de&appid=9a3719c191ce0e1e70673f892013647e&units=metric HTTP/1.1\r\nHost: www.api.openweathermap.org\r\n\r\n")
for x in string.gmatch(data, "([^\n]+)") do
if string.find(x, '"coord"') ~= nil then
for k,v in pairs(cjson.decode(x)) do
if k == "main" or k == "weather" then
print("++++++"..k.."++++++")
if type(v) == "table" then
for kz, vz in pairs(v) do
if kz == 1 or kz == 2 then
for kd,vd in pairs(vz) do
print(kd,vd)
end
else print(kz,vz) end
end end end
end end end
s:close()
不要使用那些旧的 0。9.x 预构建的二进制文件,因为它们已经过时,不再受支持并且包含很多错误。
Build your own NodeMCU firmware 最好来自 dev
分支(Espressif SDK 1.5.1)。
然后您需要习惯 NodeMCU 固件的异步事件驱动特性。 net.socket:send()
一直阻塞(即非异步)是旧 SDK 中的一个错误。
因此,您需要在 s:on('receive')
回调中处理传入的数据,并且需要在 s:on('connection')
中等待发送请求。这是模板:
conn = net.createConnection()
conn:on("receive", function(conn, payload)
-- processing data
end)
conn:on("connection", function(conn, payload)
-- conn:send
end)
conn:connect(80, "api.openweathermap.org")
在 https://nodemcu.readthedocs.io/en/dev/en/modules/net/ 查看 API 文档。
旁注:dev
分支中有一个 HTTP(客户端)模块,可简化通过 HTTP 访问远程资源的过程。
如前所述,我编写了一个连接到天气 API 并打印出结果的脚本。
当我运行逐行通过解释器(ESPlorer "Send to ESP- and run "逐行“”)时,一切正常,但是当我通过dofile()
执行它时,它无法连接到网站并失败。
我很困惑,希望你们中的一些人能发现我忽略的错误。
代码如下:
data= ""
s= net.createConnection(net.TCP, 0)
s:on("receive", function(so, da) data= da end)
s:connect(80, "api.openweathermap.org")
s:send("GET /data/2.5/weather?q=berlin,de&appid=9a3719c191ce0e1e70673f892013647e&units=metric HTTP/1.1\r\nHost: www.api.openweathermap.org\r\n\r\n")
for x in string.gmatch(data, "([^\n]+)") do
if string.find(x, '"coord"') ~= nil then
for k,v in pairs(cjson.decode(x)) do
if k == "main" or k == "weather" then
print("++++++"..k.."++++++")
if type(v) == "table" then
for kz, vz in pairs(v) do
if kz == 1 or kz == 2 then
for kd,vd in pairs(vz) do
print(kd,vd)
end
else print(kz,vz) end
end end end
end end end
s:close()
不要使用那些旧的 0。9.x 预构建的二进制文件,因为它们已经过时,不再受支持并且包含很多错误。
Build your own NodeMCU firmware 最好来自 dev
分支(Espressif SDK 1.5.1)。
然后您需要习惯 NodeMCU 固件的异步事件驱动特性。 net.socket:send()
一直阻塞(即非异步)是旧 SDK 中的一个错误。
因此,您需要在 s:on('receive')
回调中处理传入的数据,并且需要在 s:on('connection')
中等待发送请求。这是模板:
conn = net.createConnection()
conn:on("receive", function(conn, payload)
-- processing data
end)
conn:on("connection", function(conn, payload)
-- conn:send
end)
conn:connect(80, "api.openweathermap.org")
在 https://nodemcu.readthedocs.io/en/dev/en/modules/net/ 查看 API 文档。
旁注:dev
分支中有一个 HTTP(客户端)模块,可简化通过 HTTP 访问远程资源的过程。