the following code (example from http://nodemcu.com/index_en.html) stopped working:
Your code example is NOT listed as such on that page. You stitched together two individual examples from there into a single program and that fails. That's in part because one of those examples isn't really helpful anymore.
The problem is right here:
wifi.sta.config("SSID","password")
print(wifi.sta.getip())
--192.168.18.110
It suggests that wifi.sta.config
be a synchronous operation that blocks until the device got an IP address from the access point. That's not the case and, hence, it's close to impossible that by the time the next line is execute the device got an IP. If you check your serial console you probably see nil
there.
What's worse, by the time net.createServer
runs there's still no IP. Thus, the server socket isn't bound to anything and you created a zombie server.
The main message here: wait until the device got an IP and continue only then. We used to have a pretty simple template in our documentation, but for the sake of completeness it was recently updated: https://nodemcu.readthedocs.io/en/latest/en/upload/#initlua. For starters it may be stripped down to this:
-- 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
Furthermore, your server should send proper HTTP headers if you're testing from a browser. Something like this:
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)