From 880331ba23f5538d4e86a9a545f4205913039a34 Mon Sep 17 00:00:00 2001 From: Evgeny Zinoviev Date: Mon, 2 Aug 2021 15:23:46 +0300 Subject: initial --- inverter.lua | 90 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 inverter.lua (limited to 'inverter.lua') 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 -- cgit v1.2.3