-
Notifications
You must be signed in to change notification settings - Fork 13
/
ubus.lua
96 lines (71 loc) · 1.81 KB
/
ubus.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
-- SPDX-License-Identifier: MIT
-- Author: Jianhui Zhao <[email protected]>
local ubus = require 'eco.core.ubus'
local M = {}
local global_timeout = 30.0
local methods = {}
for _, method in ipairs({'close', 'call', 'reply', 'send', 'objects', 'settimeout', 'auto_reconnect'}) do
methods[method] = function(self, ...)
local con = self.con
return con[method](con, ...)
end
end
function methods:add(object, ms)
local con = self.con
for _, m in pairs(ms) do
local cb = m[1]
assert(type(cb) == 'function')
m[1] = function(req, msg)
eco.run(function()
local rc = cb(req, msg)
if type(rc) ~= 'number' then rc = 0 end
con:complete_deferred_request(req, rc)
end)
end
end
local o, err = con:add(object, ms)
if not o then
return false, err
end
return true
end
function methods:listen(event, cb)
local e, err = self.con:listen(event, function(...)
eco.run(cb, ...)
end)
if not e then
return false, err
end
return true
end
local metatable = {
__index = methods
}
function M.connect(path)
local con, err = ubus.connect(path)
if not con then
return nil, err
end
con:settimeout(global_timeout)
return setmetatable({
con = con,
}, metatable)
end
for _, method in ipairs({'call', 'send', 'objects'}) do
M[method] = function(...)
local con, err = M.connect()
if not con then
return nil, err
end
local res, err = con[method](con, ...)
con:close()
if res then
return res
end
return nil, err
end
end
function M.settimeout(timeout)
global_timeout = timeout
end
return setmetatable(M, { __index = ubus })