-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathLeweiHttpClient.lua
104 lines (92 loc) · 2.99 KB
/
LeweiHttpClient.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
--------------------------------------------------------------------------------
-- LeweiHttpClient module for NODEMCU
-- LICENCE: http://opensource.org/licenses/MIT
-- yangbo<[email protected]>
--------------------------------------------------------------------------------
--[[
here is the demo.lua:
require("LeweiHttpClient")
LeweiHttpClient.init("01","your_api_key")
tmr.alarm(0, 60000, 1, function()
--添加数据,等待上传
LeweiHttpClient.appendSensorValue("sensor1","1")
--实际发送数据
LeweiHttpClient.sendSensorValue("sensor2","3")
end)
--]]
local moduleName = ...
local M = {}
_G[moduleName] = M
local serverName = "open.lewei50.com"
local serverIP
local gateWay
local userKey
local sn
local sensorValueTable
local apiUrl = ""
local socket = nil
function M.init(gw,ukey)
if(_G["gateWay"] ~= nil) then gateWay = _G["gateWay"]
else gateWay = gw
end
if(_G["userKey"] ~= nil) then userKey = _G["userKey"]
else userKey = userkey
end
apiUrl = "UpdateSensors/"..gateWay
if(_G["sn"] ~= nil) then sn = _G["sn"]
apiUrl = "UpdateSensorsBySN/"..sn
end
sensorValueTable = {}
end
function M.appendSensorValue(sname,svalue)
sensorValueTable[""..sname]=""..svalue
end
function M.sendSensorValue(sname,svalue)
if(wifi.sta.getip()==nil)then node.restart() end
--创建一个TCP连接
socket=net.createConnection(net.TCP, 0)
--域名解析IP地址并赋值
if(serverIP == nil) then
socket:dns(serverName, function(conn, ip)
print("Connection IP:" .. ip)
serverIP = ip
end)
end
if(serverIP ~= nil) then
socket:connect(80, serverIP)
socket:on("connection", function(sck, response)
cntLen = 0
for i,v in pairs(sensorValueTable) do
cntLen = cntLen + string.len(i)+string.len(v)+23
end
cntLen = cntLen + string.len(sname)+string.len(svalue)+24
--定义数据变量格式
--HTTP请求头定义
socket:send("POST /api/V1/gateway/"..apiUrl.." HTTP/1.1\r\n")
socket:send("Host: "..serverName.."\r\n")
socket:send("Content-Length: " .. cntLen .. "\r\n")
if(userKey~=nil) then socket:send("userkey: "..userKey.."\r\n") end
socket:send("\r\n")
socket:send("[")
for i,v in pairs(sensorValueTable) do
socket:send("{\"Name\":\""..i.."\",\"Value\":\"" .. v .. "\"},")
--print(i)
--print(v)
end
socket:send("{\"Name\":\""..sname.."\",\"Value\":\"" .. svalue .. "\"}")
socket:send("]")
socket:send("\r\n")
end)
--socket:on("sent", function(sck, response)
--print(tmr.now().."sent")
--sensorValueTable = {}
--end)
--HTTP响应内容
socket:on("receive", function(sck, response)
--print(response)
PostData = nil
socket:close()
--print(node.heap())
end)
end
end