-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.lua
273 lines (247 loc) · 7.5 KB
/
main.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
mdns.register("wallsocket", {
port = 219,
service = 'iot-http',
description = 'PowerSmart Connector'
})
Buffer = dofile('buffer.lua')
HTTPParser = function()
local state = 'start'
local headerBuffer
local bodyBuffer
local req
return function(msg, conn, callback)
if (state == 'start') then
req = {}
headerBuffer = Buffer()
bodyBuffer = Buffer()
if (msg ~= nil) then
--Fill buffer
local headers, body
_,_,headers, body = msg:find("^(.*\r?\n)\r?\n(.*)$")
if (headers == nil) then
headers = msg
end
for line in headers:gmatch(".-\r?\n") do
print("adding ["..line.."] to buffer.")
headerBuffer.push(line)
end
if(body ~= nil) then
print("Adding body "..body)
headerBuffer.push("") --Signal end of headers
bodyBuffer.push(body)
end
msg = nil
end
--Check if its HTTP
if (headerBuffer.peek():match("HTTP/%d+%.%d+") ~= nil) then
_, _, req.method, req.path, req.http = headerBuffer.next():find("^(.+)%s+(.+)%s+(.+)\r?\n$")
state = 'header'
else
return nil
end
end
if(state == 'header') then
if (msg ~= nil) then
--Fill buffer
local headers, body
_,_,headers, body = msg:find("^(.*\r?\n)\r?\n(.*)$")
if (headers == nil) then
headers = msg
end
for line in headers:gmatch(".-\r?\n") do
print("Adding ["..line.."] to buffer.")
headerBuffer.push(line)
end
if (body ~= nil) then
print("Adding body "..body)
headerBuffer.push("") --Signal end of headers
bodyBuffer.push(body)
end
msg = nil --msg consumed
end
local headers = function ()
if (headerBuffer.peek() == nil) then
return nil
end
if (headerBuffer.peek():match("^\r?\n$") or headerBuffer.peek() == "") then --end of headers
state = 'body'
return nil
end
return headerBuffer.next()
end
if (req.headers == nil) then
req.headers = {}
end
for header in headers do
local key
local val
--print("Analizing header: "..header)
_,_,key,val = header:find("(.-)%s*:%s*(.+)\r?\n$")
--print("Found header: "..key..":"..val)
if(key ~= nil and val ~= nil) then --discard bad headers
req.headers[key:lower()] = val
end
end
end
if(state == 'body') then
if(msg ~= nil) then
bodyBuffer.push(msg)
msg = nil --msg consumed
end
if (req.body == nil) then
req.body = ''
end
local body = function()
return bodyBuffer.next()
end
for chunk in body do
req.body = req.body..chunk
end
--FIX: Send error "411:Needs length" if no content-length
if (req.headers['content-length'] == nil) then
state = 'start'
req.body = bodyBuffer.next()
return callback(conn, req)
end
if (req.headers['content-length'] ~= nil and tonumber(req.headers['content-length']) <= req.body:len()) then
--body ends when content-length == req.body:len()
state = 'start'
return callback(conn, req)
end
end
end
end
function route(conn, req)
local res = {
status = "200 OK",
contentType = "application/json",
connection = "keep-alive"
}
if(req == nil) then
res.status = "400 Bad Request"
res.body = '"Bad Request"'
respond(conn, res)
print("Server: Error: Received invalid HTTP request")
return
end
if (req.headers['content-length'] == nil) then
res.status = "411 Length Required"
res.body = '"Length Required"'
respond(conn, res)
print("Server: Error: Needs content length")
return
end
print("Server: Received "..req.method.." request to path: "..req.path)
for k,v in pairs(routes) do
if (k == req.path) then
if(type(v[req.method]) == "function") then
v[req.method](req, res)
respond(conn, res)
return
end
end
end
res.status = "404 Not Found"
res.body = '"Not Found"'
respond(conn, res)
return
end
function respond(conn, res)
function toHTTPCase(str)
local result = ""
str = str:sub(1,1):upper()..str:sub(2)
for token in string.gmatch(str,"(%u%l+)") do
result = result..token.."-"
end
return result:sub(1,-2)
end
local msg = "HTTP/1.1 "..res.status.."\r\n"
local body = ""
if(res.body ~= nil) then
body = res.body
res.contentLength = res.body:len()
else
res.contentLength = 0
end
res.status = nil
res.body = nil
for k, v in pairs(res) do
msg = msg..toHTTPCase(k)..": "..v.."\r\n"
end
msg = msg.."\n"..body
print("Server: Sending Response:")
print(msg)
conn:send(msg)
end
routes = {
["/"] = {
GET = function(req, res)
res.body = '{\n'..
' "name": "PowerSmart Connector",\n'..
' "devices":[\n'..
' {\n'..
' "url":"/socket0",\n'..
' "description":"Connector 1",\n'..
' "type":"boolean"\n'..
' },\n'..
' {\n'..
' "url":"/socket1",\n'..
' "description":"Connector 2",\n'..
' "type":"boolean"\n'..
' }\n'..
' ]\n'..
'}'
end
},
["/socket0"] = {
GET = function(req, res)
if(gpio.read(3)==0) then
res.body = "true"
else
res.body = "false"
end
end,
PUT = function(req, res)
if req.body == "true" then
gpio.mode(3, gpio.OUTPUT)
gpio.write(3, 0)
elseif req.body == "false" then
gpio.mode(3, gpio.OUTPUT)
gpio.write(3, 1)
else
res.status = "400 Bad Request"
res.body = '"Request should be of type boolean"'
end
end
},
["/socket1"] = {
GET = function(req, res)
if(gpio.read(4)==0) then
res.body = "true"
else
res.body = "false"
end
end,
PUT = function(req,res)
if req.body == "true" then
gpio.mode(4, gpio.OUTPUT)
gpio.write(4, 0)
elseif req.body == "false" then
gpio.mode(4, gpio.OUTPUT)
gpio.write(4, 1)
else
res.status = "404 Bad Request"
res.body = '"Request should be of type boolean"'
end
end
}
}
tcpServer=net.createServer(net.TCP)
tcpServer:listen(219,function(conn)
print("Connected to something")
local parseHTML = HTTPParser()
conn:on("receive",function(conn, msg)
print("Received data: "..msg)
parseHTML(msg, conn, route)
end)
end)