forked from db4linq/lua
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp.lua
More file actions
64 lines (58 loc) · 1.83 KB
/
http.lua
File metadata and controls
64 lines (58 loc) · 1.83 KB
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
pin1=3
pin2=4
gpio.mode(pin1,gpio.OUTPUT)
gpio.mode(pin2,gpio.OUTPUT)
function split(s, delimiter)
result = {};
for match in (s..delimiter):gmatch("(.-)"..delimiter) do
table.insert(result, match);
end
return result;
end
function urlencode(payload)
result = {};
list=split(payload,"\r\n")
--print(list[1])
list=split(list[1]," ")
--print(list[2])
list=split(list[2],"\/")
table.insert(result, list[1]);
table.insert(result, list[2]);
table.insert(result, list[3]);
return result;
end
function sendHeader(conn)
conn:send("HTTP/1.1 200 OK\r\n")
conn:send("Access-Control-Allow-Origin: *\r\n")
conn:send("Content-Type: application/json; charset=utf-8\r\n")
conn:send("Server:NodeMCU\r\n")
conn:send("Connection: close\r\n\r\n")
end
srv=net.createServer(net.TCP)
srv:listen(80,function(conn)
conn:on("receive",function(conn,payload)
list=urlencode(payload)
if (list[2]=="write") then
local pin = tonumber(list[3])
--print("Pin: "..pin)
local status = tonumber(list[4])
--print("State: "..status)
gpio.write(pin, status)
-- Response Header
sendHeader(conn)
-- Response Content
conn:send("{\"result\":\"ok\",\"digitalPin\": "..pin..", \"status\": "..gpio.read(pin).."}")
elseif (list[2]=="read") then
-- Response Header
sendHeader(conn)
-- Response Content
conn:send("{\"result\":\"ok\", \"digitalPins\": [{\"digitalPin\": "..pin1..", \"status\": "..gpio.read(pin1).."},{\"digitalPin\": "..pin2..", \"status\": "..gpio.read(pin2).."}]}")
else
-- Response Header
sendHeader(conn)
-- Response Content
conn:send("{\"result\":\"error\",\"message\": \"command not found\"}")
end
conn:close()
end)
end)