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