-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathEspOnRpcClient.lua
More file actions
119 lines (106 loc) · 2.72 KB
/
EspOnRpcClient.lua
File metadata and controls
119 lines (106 loc) · 2.72 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
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
local moduleName = ...
local M = {}
_G[moduleName] = M
local conn = nil
local devicekey = nil
local server = '115.29.202.58' -- iot.espressif.cn
local port = 8000
local rpcMapFunc = {}
local keepAliveTime = 60000
local isConnected = false
local buffer = ''
local function getStr(str, key)
for k in string.gmatch(str, '.*"'..key..'" *: *"([^"]+)".*') do
if k ~= nil then
return k
end
end
return nil
end
local function getNumber(str, key)
for k in string.gmatch(str, '.*"'..key..'" *: *([0-9.]+).*') do
if k ~= nil then
return k
end
end
return nil
end
local function identify()
local identifystr = '{"path": "/v1/device/identify/", "method": "POST", "meta": {"Authorization": "token '..devicekey..'"}}\n'
if isConnected == true then
conn:send(identifystr)
end
end
local function route(response)
buffer = buffer..response
local i, j = string.find(buffer, '\n')
if i == nil then
return false
end
local line = string.sub(buffer, 1, i-1)
buffer = string.sub(buffer, i+1, -1)
local path = getStr(line, 'path')
if path == nil then
return
end
local nonce = getNumber(line, 'nonce')
local rpc = string.gmatch(path, '/v1/device/rpc/?')()
if rpc then
action = getStr(line, 'action')
func = rpcMapFunc[action]
if func == nil then
func = rpcMapFunc['*']
end
if func ~= nil then
local result = func(action, {})
if result and nonce then
conn:send('{"status": 200, "deliver_to_device": true, "nonce": '..nonce..'}\n')
end
end
return true
end
print('unsupport command')
return false
end
local function connect()
conn = net.createConnection(net.TCP, false)
conn:on('connection', function(sck, response)
isConnected = true
identify()
end)
conn:on('disconnection', function(sck, response)
isConnected = false
connect()
end)
conn:on('receive', function(sck, response)
route(response)
end)
conn:on('sent', function(sck, response)
end)
conn:connect(port, server)
end
local function keepAlive()
local pingstr = '{"path": "/v1/ping/", "method": "GET", "meta": {"Authorization": "token '..devicekey..'"}}\n'
if isConnected == true then
conn:send(pingstr)
else
connect()
end
end
----
function M.init(key)
if key == nil or key == '' then
assert(false, 'need key')
end
devicekey = key
end
function M.run()
connect()
tmr.alarm(1, keepAliveTime, 1, function()
keepAlive()
end)
end
----
function M.onRpc(action, rpcFunc)
rpcMapFunc[action] = rpcFunc
end