Jump to content
  • 0

Sending CURL commands from a LUA coded scene


Question

Hi experts,

 

Sorry to bother you with this newbie question. Well, at least I think it is ;-) I am trying to get some data from my Fibaro devices and pushing that data to an InFluxDB by running a scene on my HC2.

 

Can someone tell me how to code the following CURL statement in a LUA scene:

 

curl -i -XPOST 'http://localhost:8086/write?db=hc2' --data-binary 'cpu_load_short,host=server02,region=us-west value=0.64 1434055562000000000'

 

I tried a POST through HTTP, but that doesn't work (most likely because of the InFluxDB version), but when using above CURL command from a Terminal session it perfectly works, but now I need to know how to do this in LUA.

 

Many thanks in advance, Sjaak

Link to post
Share on other sites

1 answer to this question

Recommended Posts

  • 0

This is example of scene called from another scene  or VD for GET, POST data to/from others system from HC2. Is no problem implement the code direct in yours scene (this is function) or call as external.

IFor use returned data is needed to add code for use it in this scene itself or put in global variable or write ex. to source scene debug message and after it retrieve, any method is good

If you need it function http:call(method, url, user, pwd , content, datas) return all necessary data add data, status_id, err_id =  http:call(method, url, user, pwd , content, datas) in place of http:call(method, url, user, pwd , content, datas) at end of code.

data - returned_data(many time s json object/table)

status_id - status of call from server (if success return 200)

err_id - error number from called server (ex 401 - no authorised)

 

if require then
   -- require("fibaro")
      require "json"
  require "LoadFibaroSceneAPI"

end


--[[
%% properties
%% events
%% globals
--]]
--[[
Call this scene (in ex.310) from any VDs or Scenes
fibaro:startScene(310 ,{"URL", "METHOD", "CONTENT_TYP", "DATA", "USER", "PASSWORD"})
URL - URL for call, in GET full url with any data like &TEST=10...
METHOD - GET or POST 
CONTENT_TYP if ommited is 'application/json'
DATA - data to send in POST method text, json, etc but it 
USER
PASSWORD 
--]]

--fibaro:startScene(310 ,{'http://192.168.1.10:1880/fromHC2', 'POST', 'application/json', '{"name":"Nick"}', '',''})
--fibaro:startScene(310 ,{'http://192.168.1.10:1880/fromHC2?name=Nick&colour=blu', 'GET', '', '', '',''})

local params = fibaro:args()




debug=false

--local httpClient = net.HTTPClient()

local http = {
    enc = function (self, data)
        local b='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
        return ((data:gsub('.', function(x) 
            local r,b='',x:byte()
            for i=8,1,-1 do r=r..(b%2^i-b%2^(i-1)>0 and '1' or '0') end
            return r;
        end)..'0000'):gsub('%d%d%d?%d?%d?%d?', function(x)
            if (#x < 6) then return '' end
            local c=0
            for i=1,6 do c=c+(x:sub(i,i)=='1' and 2^(6-i) or 0) end
            return b:sub(c+1,c+1)
        end)..({ '', '==', '=' })[#data%3+1])
    end,

-- decoding
    dec = function (self, data)
        local b='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
        data = string.gsub(data, '[^'..b..'=]', '')
        return (data:gsub('.', function(x)
            if (x == '=') then return '' end
            local r,f='',(b:find(x)-1)
            for i=6,1,-1 do r=r..(f%2^i-f%2^(i-1)>0 and '1' or '0') end
            return r;
        end):gsub('%d%d%d?%d?%d?%d?%d?%d?', function(x)
            if (#x ~= 8) then return '' end
            local c=0
            for i=1,8 do c=c+(x:sub(i,i)=='1' and 2^(8-i) or 0) end
                return string.char(c)
        end))
    end,
  
    trim = function(self, n) 
      return n:gsub("^%s*(.-)%s*$","%1")
      end,

    httpClient = net.HTTPClient(),
  	getHeaders = function(self, user, pwd, content)
    		local headers = {}
    		local c = content or 'application/json'
    		headers['Content-Type'] = c
    		if (user and user ~= "") then headers["Authorization"] = 'Basic '..self:enc(user..":"..pwd) end
    		return headers
    end,
  	manageReturn = function(self, resp)
            response = "OK"
           -- print("resp : ", json.encode(resp))
            if (type(resp) == "table" and resp.data) then
            	status = self:trim(json.encode(resp.status)) --
      			  response = self:trim(json.encode(resp.data))
            else 
            	response = resp.data --
      			  status = resp.status
            end
          if debug==true then
            print('Returned: '..response)
            print('Status  : '..status)
            end
    end,
--    m - method, u - user, p - password, c - content, d - data
  	getOptions = function(self, m, u, p, c, d)
            local opt = {
      				method = m,
    				success = function(response) self:manageReturn(response) end,
    				error = function(err) print('>>>> Error = ' .. err .. ' <<<<'); problem=err end, 
      				["options"] = {}
    		} 
            local h = self:getHeaders(u, p, c)    
            if (h) then opt.options["headers"] = h end
            if (d) then opt.options["data"] = d end
            if (m) then opt.options["method"] = m end            
          if debug==true then  
            print('Header:'..json.encode(opt.options.headers))
            print('Method:'..json.encode(opt.options.method))
            print('Data  :'..json.encode(opt.options.data))
            print('Method old api:'..json.encode(opt.method))
            end
    		return opt
    end,
--use call function, next get, post not used    
    get = function(self, url, user, pwd, content)
        self.httpClient:request(url, self:getOptions("GET", user, pwd , content)  )   ;   
 --[[ version without call getOptions()       
        httpClient:request(url, {
    				success = function(response) self:manageReturn(response) end,
    				error = function(err) tools.error('   error = ' .. err) end,
        		options = {
                      method = 'GET',
                      headers = { 
                              ["content-type"] = content,
                              ["Authorization"] = 'Basic '..pwd
                              }                     
                      },
      	})
 --]]   
    end,
  	
    post = function(self, url, user, pwd, content, datas)
        self.httpClient:request(url, self:getOptions("POST", user, pwd , content, datas)  )   ;   
 
 --[[ version without call getOptions() 
          self.httpClient:request(url , {
          success = function(response) self:manageReturn(response) end,
          error = function(err) tools.error('   error = ' .. err) end,
          options = {
                    method = 'POST',
                    headers = { 
                              ["content-type"] = content,
                              ["Authorization"] = 'Basic '..self:enc(user..":"..pwd)
                              },
                    data = datas
                    }
        })
      ;
   --]] 
    end,  	

  	call = function(self, method, url, user, pwd, content, datas)
            self.httpClient:request(url, self:getOptions(method, user, pwd , content, datas)  )   ;   
            return response, status, problem
--[[            
            if (method == "GET") then 
      			print("Call via GET")
                self:get(url, user, pwd, content) 
            end
            if (method == "POST") then 
       			print("Call via POST")
                self:post(url, user, pwd, content, datas) 
            end
--]]    
    end,

}





--GEAPlugin = {}
--datas={}


local url     	= params[1] or ""
local method 	= params[2] or "GET"
local content 	= params[3] or "application/json"
local datas	  	= params[4] or ""
local user 	  	= params[5] or ""
local pwd		= params[6] or ""


--[[
FOR TEST
GET data examaple:
local method 	= "GET"
local url =  "http://192.168.1.10:1880/HC2?name=Nick&colour=blue"
local content = "text/plain" --"multipart/form-data" 
local content = "application/json"

POST data example:
local method 	= "POST"
local url =  "http://192.168.1.10:1880/HC2"
local datas	= '{"name":"Nick", "colour":"blue"}'
-- if login data set
local user = "user"
local pwd	= "pass" 
--]]

http:call(method, url, user, pwd , content, datas)

print(method .. " : " .. url .. ' : ' ..datas)



 

Edited by drboss
Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Answer this question...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...