-- Simple NodeMCU web server (done is a not so nodeie fashion :-)
--
-- Written by Scott Beasley 2015
-- Open and free to change and use. Enjoy.
--

-- Your Wifi connection data
-- local SSID = "xxxxxxxx"
-- local SSID_PASSWORD = "xxxxxxxx"

local function connect (conn)
   conn:on ("receive", function (conn, req_data)
      print("-----------------")
      print(req_data)
      --local query_data
      --query_data = get_http_req (req_data)
      --print (query_data["METHOD"] .. " " .. " " .. query_data["User-Agent"])
      conn:send ("<html><h1>Hello World from ESP8266 and NodeMCU!!</h1></html>")
   end)
   conn:on ("sent", function(conn)
      conn: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.ap.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 reamaining ":" 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)
-- wifi.sta.autoconnect (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)

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