simpleHTTPD.lua 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. -- Simple NodeMCU web server (done is a not so nodeie fashion :-)
  2. --
  3. -- Written by Scott Beasley 2015
  4. -- Open and free to change and use. Enjoy.
  5. --
  6. -- Your Wifi connection data
  7. -- local SSID = "xxxxxxxx"
  8. -- local SSID_PASSWORD = "xxxxxxxx"
  9. local function connect (conn)
  10. conn:on ("receive", function (conn, req_data)
  11. print("-----------------")
  12. print(req_data)
  13. --local query_data
  14. --query_data = get_http_req (req_data)
  15. --print (query_data["METHOD"] .. " " .. " " .. query_data["User-Agent"])
  16. conn:send ("<html><h1>Hello World from ESP8266 and NodeMCU!!</h1></html>")
  17. end)
  18. conn:on ("sent", function(conn)
  19. conn:close()
  20. end)
  21. end
  22. function wait_for_wifi_conn ( )
  23. tmr.alarm (1, 1000, 1, function ( )
  24. if wifi.sta.getip ( ) == nil then
  25. print ("Waiting for Wifi connection")
  26. else
  27. tmr.stop (1)
  28. print ("ESP8266 mode is: " .. wifi.getmode ( ))
  29. print ("The module MAC address is: " .. wifi.ap.getmac ( ))
  30. print ("Config done, IP is " .. wifi.sta.getip ( ))
  31. end
  32. end)
  33. end
  34. -- Build and return a table of the http request data
  35. function get_http_req (instr)
  36. local t = {}
  37. local first = nil
  38. local key, v, strt_ndx, end_ndx
  39. for str in string.gmatch (instr, "([^\n]+)") do
  40. -- First line in the method and path
  41. if (first == nil) then
  42. first = 1
  43. strt_ndx, end_ndx = string.find (str, "([^ ]+)")
  44. v = trim (string.sub (str, end_ndx + 2))
  45. key = trim (string.sub (str, strt_ndx, end_ndx))
  46. t["METHOD"] = key
  47. t["REQUEST"] = v
  48. else -- Process and reamaining ":" fields
  49. strt_ndx, end_ndx = string.find (str, "([^:]+)")
  50. if (end_ndx ~= nil) then
  51. v = trim (string.sub (str, end_ndx + 2))
  52. key = trim (string.sub (str, strt_ndx, end_ndx))
  53. t[key] = v
  54. end
  55. end
  56. end
  57. return t
  58. end
  59. -- String trim left and right
  60. function trim (s)
  61. return (s:gsub ("^%s*(.-)%s*$", "%1"))
  62. end
  63. -- Configure the ESP as a station (client)
  64. wifi.setmode (wifi.STATION)
  65. -- wifi.sta.config (SSID, SSID_PASSWORD)
  66. -- wifi.sta.autoconnect (1)
  67. -- Hang out until we get a wifi connection before the httpd server is started.
  68. wait_for_wifi_conn ( )
  69. -- Create the httpd server
  70. svr = net.createServer (net.TCP)
  71. -- Server listening on port 80, call connect function if a request is received
  72. svr:listen (80, connect)