Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- start a web server. Return the web server object
- function startWeb(cfg)
- -- define member variables
- local config = cfg
- local state = "inactive"
- local server = net.createServer(net.TCP)
- -- define functions
- local close = function()
- server:close()
- state = "inactive"
- end
- local getStatus = function()
- return state
- end
- local parseRequest = function(request)
- -- the first line of the request is in the form METHOD URL PROTOCOL
- _, _, method, url = string.find(request, "(%a+)%s([^%s]+)")
- _, _, path, queryString = string.find(url, "([^%s]+)%?([^%s]+)")
- if queryString then
- query = {}
- for name, value in string.gfind(queryString, "([^&=]+)=([^&=]+)") do
- query[name] = value
- end
- else
- path = url
- query = nil
- end
- return { method = method, url = url, path = path, query = query, queryString = queryString}
- end
- -- start listening for requests
- server:listen(80,function(s)
- s:on("receive", function(s, rawRequest)
- local isopen = false
- request = parseRequest(rawRequest)
- print("Request received: ", request.method, request.url,request.path)
- if config.pages[request.path] then
- response = config.pages[request.path](request)
- status = "200 OK"
- else
- response = "<html><body><p>" .. request.url .. " doesn't exist.</p></body></html>"
- status = "404 Not Found"
- end
- headers = "HTTP/1.1 " .. status .. "\r\nConnection: keep-alive\r\nCache-Control: private, no-store\r\nContent-Length: " .. string.len(response) .. "\r\n\r\n"
- s:send(headers .. response)
- end)
- s:on("sent", function(s)
- if not isopen then
- isopen = true
- file.open("led_gif.html", "r")
- end
- local data = file.read()
- if data then
- s:send(data)
- else
- file.close()
- s:close()
- s = nil
- end
- end)
- end)
- state = "listening"
- return { getStatus = getStatus, close = close }
- end
- pages = {}
- pages["/led.gif"] = function(request)
- file.open("led.gif")
- X = file.read()
- file.close()
- tmr.wdclr()
- return X , "image/gif"
- end
- pages["/"] = function(request)
- file.open("led_gif.html")
- X=file.read()
- file.close()
- tmr.wdclr()
- X = X ..F()
- return X
- end - See more at: http://www.esp8266.com/viewtopic.php?f=24&t=1334#sthash.w0UC7RQR.dpuf
- pages["/test.svg"] = function(request)
- local out = "<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" width=\"400\" height=\"150\">\n";
- out = out.."<rect width=\"400\" height=\"150\" fill=\"rgb(250, 230, 210)\" stroke-width=\"1\" stroke=\"rgb(0, 0, 0)\" />\n";
- out = out.."<g stroke=\"black\">\n";
- y = math.random() % 130;
- for x=1, 390, 10 do
- y2 = math.random() % 130;
- print(x);
- print(" ");
- print(y2);
- out= out..string.format("<line x1=\"%d\" y1=\"%d\" x2=\"%d\" y2=\"%d\" stroke-width=\"1\" />\n", x, 140 - y, x + 10, 140 - y2)
- y = y2;
- end
- out = out.."</g>\n</svg>\n";
- return out , "image/svg+xml"
- end
Advertisement
Add Comment
Please, Sign In to add comment