Skip to content

Instantly share code, notes, and snippets.

@georgyangelov
Last active January 25, 2017 17:39
Show Gist options
  • Save georgyangelov/91f17ce4a842ccb834b9b839adcf6b52 to your computer and use it in GitHub Desktop.
Save georgyangelov/91f17ce4a842ccb834b9b839adcf6b52 to your computer and use it in GitHub Desktop.
function parse(request)
local _, _, method, path, vars = string.find(request, "([A-Z]+) (.+)?(.+) HTTP")
if not method then
_, _, method, path = string.find(request, "([A-Z]+) (.+) HTTP")
end
local _GET = {}
if vars then
for k, v in string.gmatch(vars, "(%w+)=(%w+)&*") do
_GET[k] = v
end
end
local json
if method == 'POST' then
_, _, json = string.find(request, '\n({.*})$')
json = json and cjson.decode(json)
end
return {
method = method,
path = path,
params = _GET,
body = json
}
end
function readFile(name)
file.open(name);
local buf = file.read();
file.close();
return buf;
end
function startServer()
local index = readFile("index.html")
local app = readFile("app.js")
local status = {
distance = 0,
yellow = false,
red = false
}
local statusResponse = ""
function buildResponse()
statusResponse = "HTTP/1.1 200 OK\nContent-Type: application/json\n\n" .. cjson.encode(status) .. "\n"
end
buildResponse();
function onReceive(client, request)
local r = parse(request)
if (r.method == "GET" and r.path == "/status") then
client:send(statusResponse)
elseif (r.method == "GET" and r.path == "/") then
client:send(index)
elseif (r.method == "GET" and r.path == "/app.js") then
client:send(app)
elseif (r.method == "POST" and r.path == "/io") then
if (r.body) then
if r.body.red then
status.red = r.body.red
end
if r.body.yellow then
status.yellow = r.body.yellow
end
end
client:send(statusResponse)
else
local buf = "Oooops"
client:send(buf)
end
client:close()
end
srv = net.createServer(net.TCP, 5)
srv:listen(80, function(connection)
connection:on("receive", onReceive)
end)
end
wifi.setmode(wifi.STATION);
wifi.sta.config("********", "************");
startServer();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment