NodeMCU: 构建新固件后负责创建服务器的代码停止工作

自从我通过https://nodemcu-build.com/和pyflasher从0.9.6-dev_20150704版本升级到较新版本后,以下代码(来自http://nodemcu.com/index_en.html)停止工作:

print(wifi.sta.getip())
--nil
wifi.setmode(wifi.STATION)
wifi.sta.config("SSID","password")
print(wifi.sta.getip())
--192.168.18.110

--一个简单的HTTP服务器
srv=net.createServer(net.TCP)
srv:listen(80,function(conn)
    conn:on("receive",function(conn,payload)
    print(payload)
    conn:send("<h1> Hello, NodeMcu.</h1>")
    end)
end)

明确地,连接似乎可以工作(因为我在路由器的列表上看到了MCU),但是当我在浏览器中键入MCU的相应地址时,它无法连接到服务器。 有什么想法如何修复它吗?

点赞
用户131929
用户131929

下面的代码(来自http://nodemcu.com/index_en.html的示例)停止了工作:

您的代码示例在该页面上未列出。您将两个单独的示例从那里拼接成一个程序,导致失败。这在某种程度上是因为其中一个示例已不再有用。

问题在这里:

wifi.sta.config("SSID","password")
print(wifi.sta.getip())
--192.168.18.110

它建议wifi.sta.config是一个同步操作,会阻塞,直到设备从接入点获取到IP地址。这不是事实,因此,当执行下一行时,设备几乎不可能获得IP。如果您检查串行控制台,您可能在那里看到nil

更糟糕的是,到net.createServer运行时仍然没有IP。因此,服务器套接字未绑定到任何内容,您创建了一个僵尸服务器。

主要消息在这里:等待设备获得IP,然后才继续。我们曾经在文档中有一个非常简单的模板,但为完整起见,它最近进行了更新:https://nodemcu.readthedocs.io/en/latest/en/upload/#initlua。对于新手来说,可能可以削减到这个程度:

-- load credentials, 'SSID' and 'PASSWORD' declared and initialize in there
dofile("credentials.lua")

function startup()
  if file.open("init.lua") == nil then
    print("init.lua deleted or renamed")
  else
    print("Running")
    file.close("init.lua")
    -- the actual application is stored in 'application.lua'
    -- dofile("application.lua")
  end
end

-- Define WiFi station event callbacks
wifi_got_ip_event = function(T)
  -- Note: Having an IP address does not mean there is internet access!
  -- Internet connectivity can be determined with net.dns.resolve().
  print("Wifi connection is ready! IP address is: " .. T.IP)
  print("Startup will resume momentarily, you have 3 seconds to abort.")
  print("Waiting...")
  tmr.create():alarm(3000, tmr.ALARM_SINGLE, startup)
end

-- Register WiFi Station event callbacks
wifi.eventmon.register(wifi.eventmon.STA_GOT_IP, wifi_got_ip_event)

print("Connecting to WiFi access point...")
wifi.setmode(wifi.STATION)
wifi.sta.config({ ssid = SSID, pwd = PASSWORD, save = true })
-- wifi.sta.connect() not necessary because config() uses auto-connect=true by default

此外,如果您正在从浏览器测试,则您的服务器应发送适当的HTTP标头。例如:

local content = "<h1>Hello, world!</h1>"
conn:send("HTTP/1.0 200 OK\r\nContent-Type: text/html\r\nConnection: close\r\n\r\n" .. content)
2017-05-28 19:45:49