Wordclock/webserver.lua

106 lines
2.6 KiB
Lua
Raw Normal View History

--TODO:
configFile="config.lua"
sentBytes=0
2016-12-17 02:09:23 +01:00
function sendPage(conn, nameOfFile)
2016-12-29 21:01:15 +01:00
conn:on("sent", function(conn)
if (sentBytes == 0) then
conn:close()
print("Page sent")
2016-12-29 21:01:15 +01:00
else
sendPage(conn, nameOfFile)
end
end)
2016-12-17 02:09:23 +01:00
2016-12-29 21:01:15 +01:00
if file.open(nameOfFile, "r") then
local buf=""
if (sentBytes <= 0) then
buf=buf .. "HTTP/1.1 200 OK\r\n"
buf=buf .. "Content-Type: text/html\r\n"
buf=buf .. "Connection: close\r\n"
buf=buf .. "Date: Thu, 29 Dec 2016 20:18:20 GMT\r\n"
buf=buf .. "\r\n\r\n"
end
2016-12-29 21:01:15 +01:00
-- amount of sent bytes is always zero at the beginning (so no problem)
file.seek("set", sentBytes)
local line = file.readline()
2016-12-17 02:09:23 +01:00
-- TODO replace the tokens in the line
while (line ~= nil) do
buf = buf .. line
2016-12-29 21:01:15 +01:00
-- increase the amount of sent bytes
sentBytes=sentBytes+string.len(line)
2016-12-17 02:09:23 +01:00
-- Sent after 1k data
2016-12-29 21:01:15 +01:00
if (string.len(buf) >= 500) then
2016-12-17 02:09:23 +01:00
line=nil
2016-12-29 21:01:15 +01:00
conn:send(buf)
-- end the function, this part is sent
return
2016-12-17 02:09:23 +01:00
else
-- fetch the next line
2016-12-29 21:01:15 +01:00
line = file.readline()
2016-12-17 02:09:23 +01:00
end
end
2016-12-29 21:01:15 +01:00
--reset amount of sent bytes, as we reached the end
sentBytes=0
-- send the rest
conn:send(buf)
2016-12-17 02:09:23 +01:00
end
2016-12-29 21:01:15 +01:00
2016-12-17 02:09:23 +01:00
end
function startWebServer()
srv=net.createServer(net.TCP)
srv:listen(80,function(conn)
conn:on("receive", function(conn,payload)
if (payload:find("GET /") ~= nil) then
--here is code for handling http request from a web-browser
2016-12-29 21:01:15 +01:00
if (sendPage ~= nil) then
2016-06-19 17:48:39 +02:00
print("Loading webpage ...")
2016-12-29 21:01:15 +01:00
-- Load the sendPagewebcontent
sendPage(conn, "webpage.html")
2016-06-19 17:48:39 +02:00
end
else if (payload:find("POST /") ~=nil) then
2016-12-29 21:01:15 +01:00
-- Fixme handle it later
print("POST request detected")
else
2016-06-19 17:48:39 +02:00
print("Hello via telnet")
--here is code, if the connection is not from a webbrowser, i.e. telnet or nc
global_c=conn
function s_output(str)
if(global_c~=nil)
then global_c:send(str)
end
end
node.output(s_output, 0)
global_c:on("receive",function(c,l)
node.input(l)
end)
global_c:on("disconnection",function(c)
node.output(nil)
global_c=nil
end)
2016-06-18 23:19:39 +02:00
print("Welcome to Word Clock")
end
end
end)
conn:on("disconnection", function(c)
node.output(nil) -- un-register the redirect output function, output goes to serial
--reset amount of sent bytes, as we reached the end
sentBytes=0
end)
end)
end