Jump to content
  • 0

http request in a HC3 scene


Question

Hello,

I'm trying to "convert" this LUA script in a scene, but my trouble cames from the fact that I don't know how to send an http request in a scene.

Here is the script I use in a device (and it works find):

    local texte = string.format("%s %s", tostring(os.date('%H:%m', os.time() )), "HC3 : This is a test.")
    local address = string.format("http://192.168.0.0/write?color=%s&bg=%s&t=%s", "black", "white",texte)

    http:request(address, {
            options={
                method = 'GET'
            },
            success = function(response)
                print(response.data)
            end,
            error = function(error)
                self:debug('error: ' .. json.encode(error))
            end
        })

The goal, is to send a time stamped notification in a remote web server when a scene is launch, but maybe I'm on a wrong way ?

 

Thanks for your help.

Alex.

Link to post
Share on other sites

5 answers to this question

Recommended Posts

  • 0

Thanks for you answer @SmartHomeEddy

In the solution you gave, you use a QuickApp that trigger the request and in the scene you call the Quickapp. That's can do the job, but is there a shorten solution to send the request directely in the scene ?

Link to post
Share on other sites
  • 0
1 hour ago, AlexPeret said:

but is there a shorten solution to send the request directely in the scene ?

 

sure, e.g.

 

local Host   = "192.168.199.134"
local Port   = "80"
local tcpTimeout = 2000
local srvUser = "admin"
local srvPwd = "admin"

local texte = string.format("%s %s", tostring(os.date('%H:%m', os.time() )), "HC3 : This is a test.")
local mymsg = string.format("?color=%s&bg=%s&t=%s", "black", "white",texte)

function urlencode(str)
  if (str) then
    str = string.gsub (str, "\n", "\r\n")
    str = string.gsub (str, "([^%w %-%_%.%~])", function (c) return string.format ("%%%02X", string.byte(c)) end)
    str = string.gsub (str, " ", "+")
  end
  return str	
end

function base64(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

local bauth = 'Basic '..base64(srvUser..":"..srvPwd)
local url = "http://" .. Host .. ":" .. Port .. "/write" .. urlencode(mymsg)

net.HTTPClient():request(url, {
    options={
      method = 'GET',
      headers = {
          ["Authorization"] = bauth
        },
      timeout = tcpTimeout,
    },
    success = function(response) 
            print(response.status)
            print(response.data)
    end,
    error = function(message)
            print("error:", message)
    end
})

if you don't need any authorization, you might remove the base64 and headers = {.....} part

  • Like 1
Link to post
Share on other sites
  • 0

Whaou ! thanks very much @tinman that's do the job !

 

By the way is there a solution to include my own librarie ? I will used a lot of times the url_encode function and I don't want to copy-paste it everywhere, and I think it can more powerfull just to include a cutom librarie with this code (and some other functions for latter).

Edited by AlexPeret
Link to post
Share on other sites
  • 0

Obs: Sorry for possible errors ... I used the google translator.

 

Hello.

 

I migrated from HC2 to HC3. At HC2 I had a generic scene that was called by several others to send me a message on the telegram.

 

Example: Someone touched the campaign, I received a message on Telegram: "The campaign has been activated". The door was opened, I received a message "the door was opened".

 

It used a global variable in which the main scene determined the variable telegram and, after that, the generic scene that sent the message to the telegram was called.

 

However, with HC3, this scene stopped working.

 

I made some changes to the LUA code, but I can't get the message on the telegram.

 

The error message I get is:

 

[DEBUG] [SCENE54]: 400
[DEBUG] [SCENE54]: {"ok": false, "error_code": 400, "description": "Bad Request: message text is empty"}

 

I put one more message in this code to see the value of the variable Telegram and url, and both are not reset.

 

fibaro.debug("URL é", url)
fibaro.debug("MSG é", msg)

 

Please, could someone guide me where I was missing the LUA code below? Thank you.

------------------------------------------------------------------------------

--[[
%% properties
%% globals
Telegram
--]]

 

local token = "nr. TOKEN of TELEGRAM"
local chat_id = "nr. chat id"
local url = "https://api.telegram.org/bot"..token.."/sendMessage?chat_id="..chat_id.."&text="

 

if (tonumber(fibaro.getGlobalVariable("Telegram")) == 0) then
  fibaro:abort();
end

 

local selfhttp = net.HTTPClient({timeout=2000})

 

local msg = fibaro.getGlobalVariable("Telegram")

 

url = url .. msg

 

selfhttp:request(url, {
  options={
    method = 'GET',
    headers = selfhttp.controlHeaders,
    data = requestBody,
    timeout = 5000
  },
 success = function(response) 
            print(response.status)
            print(response.data)
    end,
    error = function(message)
            print("error:", message)
    end
})

 

fibaro.debug("URL é", url)
fibaro.debug("MSG é", msg)

 

--Reset the global Telegram variable to 0


fibaro.setGlobalVariable("Telegram", "0")

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...