nodemcu – simple webserver

I’ve modified and updated this source:

local SSID = "my_wifi_ssid"
local SSID_PASSWORD = "my_wifi_password"

local function http_header(conn)
  conn:send('HTTP/1.1 200 OK\n\n')
  conn:send('<!DOCTYPE HTML>\n')
  conn:send('<html>\n')
  conn:send('<head><meta  content="text/html; charset=utf-8">\n')
  conn:send('<title>ESP8266 znouza test</title></head>\n')
end

local function connect (conn, data)
   local query_data

   conn:on ("receive",
      function (cn, req_data)
         query_data = get_http_req (req_data)
         print (query_data["METHOD"] .. " " .. " " .. query_data["User-Agent"])
         http_header(cn)
         cn:send ("<body>")
         cn:send ("<h1>Hello World from ESP8266 and NodeMCU!!</h1>")
         cn:send ("</body></html>")
         -- Close the connection for the request
         cn:close ( )
      end)
end

function wait_for_wifi_conn ( )
   tmr.alarm (1, 1000, 1, function ( )
      if wifi.sta.getip ( ) == nil then
         print ("Waiting for Wifi connection")
      else
         tmr.stop (1)
         print ("ESP8266 mode is: " .. wifi.getmode ( ))
         print ("The module MAC address is: " .. wifi.sta.getmac ( ))
         print ("Config done, IP is " .. wifi.sta.getip ( ))
      end
   end)
end

-- Build and return a table of the http request data
function get_http_req (instr)
   local t = {}
   local first = nil
   local key, v, strt_ndx, end_ndx

   for str in string.gmatch (instr, "([^\n]+)") do
      -- First line in the method and path
      if (first == nil) then
         first = 1
         strt_ndx, end_ndx = string.find (str, "([^ ]+)")
         v = trim (string.sub (str, end_ndx + 2))
         key = trim (string.sub (str, strt_ndx, end_ndx))
         t["METHOD"] = key
         t["REQUEST"] = v
      else -- Process and remaining ":" fields
         strt_ndx, end_ndx = string.find (str, "([^:]+)")
         if (end_ndx ~= nil) then
            v = trim (string.sub (str, end_ndx + 2))
            key = trim (string.sub (str, strt_ndx, end_ndx))
            t[key] = v
         end
      end
   end

   return t
end

-- String trim left and right
function trim (s)
  return (s:gsub ("^%s*(.-)%s*$", "%1"))
end

-- Configure the ESP as a station (client)
wifi.setmode (wifi.STATION)
wifi.sta.config (SSID, SSID_PASSWORD,1)

-- Hang out until we get a wifi connection before the httpd server is started.
wait_for_wifi_conn ( )

-- Create the httpd server
svr = net.createServer (net.TCP, 30)

-- Server listening on port 80, call connect function if a request is received
svr:listen (80, connect)

2 thoughts on “nodemcu – simple webserver

  1. Hi Tom – I’m playing around with ESP8266 flashed with NodeMCU so this Lua program was a boon to me! However, it isn’t working as it should. The first error is line 76. Apparently, this command has now been deprecated (see https://github.com/nodemcu/nodemcu-firmware/issues/2082) and so I replaced it with the recommended . I save the file as init.lua using ESPlorer, and, sure enough the systems starts and connects to my WLAN. However, when I open a web browser (say Firefox), I see the information about the browser ‘printed’ “GET Mozilla/5.0 (Windows NT 6.1; Win64; x64 rv:57.0) etc” but the webpage refuses to connect with a comment “The connection to the server was reset while the page was loading.”. I’m really getting frustrated as I have tried numerous programs – and I must say, yours is by far the easiest to understand!! – but they all exhibit this problem, even though they will connect to my wireless AP (I can always ping the ESP device with no problems) My device is powered by Lua 5.1.4 on SDK 2.1.0(116b762). Any comments you might have would be gratefully received! Thanks so much – Mike

Leave a Reply

Your email address will not be published. Required fields are marked *

9 × = 54