1 -- Copyright 2009 Steven Barth <steven@midlink.org>
2 -- Licensed to the public under the Apache License 2.0.
4 local util = require "luci.util"
5 local json = require "luci.json"
6 local ltn12 = require "luci.ltn12"
7 local nixio = require "nixio", require "nixio.util"
9 local tostring, assert, setmetatable = tostring, assert, setmetatable
14 RQLIMIT = 32 * nixio.const.buffersize
18 function Client.__init__(self, fd, v1)
20 self.uniqueid = tostring(self):match("0x([a-f0-9]+)")
25 function Client.request(self, method, params, notification)
26 local oldchunk = self.decoder and self.decoder.chunk
27 self.decoder = json.ActiveDecoder(self.fd:blocksource(nil, RQLIMIT))
28 self.decoder.chunk = oldchunk
30 local reqid = self.msgid .. self.uniqueid
31 local reqdata = json.Encoder({
32 id = (not notification) and (self.msgid .. self.uniqueid) or nil,
33 jsonrpc = (not self.v1) and "2.0" or nil,
37 ltn12.pump.all(reqdata:source(), self.fd:sink())
38 if not notification then
39 self.msgid = self.msgid + 1
40 local response = self.decoder:get()
41 assert(response.id == reqid, "Invalid response id")
42 if response.error then
43 error(response.error.message or response.error)
45 return response.result
49 function Client.proxy(self, prefix)
51 return setmetatable({}, {
52 __call = function(proxy, ...)
53 return self:request(prefix, {...})
55 __index = function(proxy, name)
56 return self:proxy(prefix .. name .. ".")