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
|
local socket = require('socket') --luasocket
local function trim(s)
return s:gsub("^%s*(.-)%s*$", "%1")
end
local function split(s, sep)
local t = {}
for str in string.gmatch(s, "([^"..sep.."]+)") do
table.insert(t, str)
end
return t
end
local Inverter = {}
Inverter.__index = Inverter
function Inverter.create(host, port)
assert(host ~= nil, 'host cannot be nil')
assert(type(port) == 'number', 'port must be a number')
local client = {}
client.host = host
client.port = port
client.tcp = socket.tcp()
setmetatable(client, Inverter)
return client
end
function Inverter:connect()
local ok, err = self.tcp:connect(self.host, self.port)
if not ok then
return ok, err
end
self:format('json')
return true
end
function Inverter:disconnect()
self.tcp:close()
end
function Inverter:format(format)
data = 'format ' .. format
if not self:_write(data) then
return nil
end
return self:_read_response()
end
function Inverter:exec(command, arguments)
data = 'exec ' .. command
if arguments then
data = data .. ' ' .. table.concat(arguments, ' ')
end
if not self:_write(data) then
return nil
end
return self:_read_response()
end
function Inverter:_write(data)
return self.tcp:send(data .. '\r\n')
end
function Inverter:_read_response()
buf = ''
while (true) do
readed = self.tcp:receive()
if readed == '' then
break
end
buf = buf .. readed .. '\r\n'
end
buf = trim(buf)
response = split(buf, '\r\n')
status = response[1]
table.remove(response, 1)
body = table.concat(response, '\r\n')
return status == 'ok', body
end
return Inverter
|