shithub: scripts

ref: bc762e9c9294990c0d2480295637c792363dcc8c
dir: /lib/lua/r2pipe.lua/

View raw version
---
-- r2pipe for lua
---

local net = require "net"
local json = require "json"

local r2pipe = {}

---
-- tcp protocol
---

local R2Tcp = {
  new = function(self, host, port)
    local o = {}
    setmetatable(o, self)
    self.__index = self

    o.socket = net.Socket:new()
    o.host = host
    o.port = port

    return o

  end,

  send = function(self, data)
    self.socket:dial(self.host, self.port)
    return self.socket:send(data)
  end,

  read = function(self)
    local b, done
    done = false

    status, b = self.socket:receive_all()
    if not(status) then
      return false, b
    end

    self.socket:close()
    return true, b
  end,

  close = function(self)
    self.socket:close()
  end,
}

---
-- R2Comm
---

local R2Comm = {
  new = function(self, proto)
    local o = {}
    setmetatable(o, self)
    self.__index = self
    o.proto = proto
    return o
  end,

  cmd = function(self, cmd)
    local status, err, response
    status, err = self.proto:send(string.format("%s\n", cmd))
    if not(status) then
      return false, err
    end
    status, response = self.proto:read()
    if not(status) then
      return false, response
    end
    return true, response
  end,

  cmdj = function(self, cmd)
    local status, response
    status, response = self.proto:send(string.format("%s\n", cmd))
    if not(status) then
      return false, response
    end
    status, response = self.proto:read()
    if not(status) then
      return false, response
    end
    status, response = json.parse(response)
    if not(status) then
      return false, response
    end
    return true, response
  end,

  close = function(self)
    self.proto:close()
  end,
}

local r2pipe = {
  R2Tcp = R2Tcp,
  R2Comm = R2Comm,
}

return r2pipe