diff options
author | Evgeny Zinoviev <me@ch1p.io> | 2021-08-02 15:23:46 +0300 |
---|---|---|
committer | Evgeny Zinoviev <me@ch1p.io> | 2021-08-02 15:28:15 +0300 |
commit | 880331ba23f5538d4e86a9a545f4205913039a34 (patch) | |
tree | f347c481b6f9a6e44f77ca570ff30c08249dd4dd /inverter.lua |
Diffstat (limited to 'inverter.lua')
-rw-r--r-- | inverter.lua | 90 |
1 files changed, 90 insertions, 0 deletions
diff --git a/inverter.lua b/inverter.lua new file mode 100644 index 0000000..0a38331 --- /dev/null +++ b/inverter.lua @@ -0,0 +1,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 |