Jump to content

Welcome to Smart Home Forum by FIBARO

Dear Guest,

 

as you can notice parts of Smart Home Forum by FIBARO is not available for you. You have to register in order to view all content and post in our community. Don't worry! Registration is a simple free process that requires minimal information for you to sign up. Become a part of of Smart Home Forum by FIBARO by creating an account.

 

As a member you can:

  •     Start new topics and reply to others
  •     Follow topics and users to get email updates
  •     Get your own profile page and make new friends
  •     Send personal messages
  •     ... and learn a lot about our system!

 

Regards,

Smart Home Forum by FIBARO Team


  • 1

Scene for getting electricity prices from Tibber


mortesan

Question

I have created a LUA scene to fetch the current electricity prices from Tibber, I then store the values in global variables. This can again be used to control appliances according to prices. 

 

Tibber api: 

Please login or register to see this link.

 

In the scene below I have used a demo token from tibber. 

 

LUA scene: 

local http = net.HTTPClient();
http:request('https://api.tibber.com/v1-beta/gql',{
    options = {
      method = 'POST',
      headers = {
        ["Content-Type"] = 'application/json',
        ["Authorization"] = 'Bearer d1007ead2dc84a2b82f0de19451c5fb22112f7ae11d19bf2bedb224a003ff74a'
      },
      data = '{ "query": "{viewer {homes {currentSubscription {priceInfo {current {total energy tax startsAt }}}}}}" }'
    },
    
     success = function(resp)
          if (resp.status == 200) or (resp.status == 201) then            
              local data = json.decode(resp.data);
            fibaro:debug(resp.data);
            print  ("price: "..tostring(data.data.viewer.homes[1].currentSubscription.priceInfo.current.total));
            fibaro:setGlobal('Strompris',data.data.viewer.homes[1].currentSubscription.priceInfo.current.total);
          else
               fibaro:debug(resp.status);
              fibaro:debug("ERR");

          end
    end, 
    error = function(error)
        fibaro:debug"ERROR"
          fibaro:debug(error)
      

    end     
})

 


            fibaro:sleep (90000); 
              fibaro:startScene(370);

 

I use the energy price in a virtual device to show the current vaule, and todays and yesterdays high low. 

 

Please login or register to see this image.

/monthly_2018_05/image.png.4e5bb541b72603e00cf1c1cdfc22aac6.png" alt="image.png.4e5bb541b72603e00cf1c1cdfc22aac6.png" />

  • Like 2
Link to comment
Share on other sites

20 answers to this question

Recommended Posts

  • 1
  • Inquirer
  • The LUA code in the first post should work to fetch the prices, if that is not working then maybe there is something wrong with the Bearer code for your Tibber. You also need to add a variable and send the price to the correct variable, as you see from the code I am using setGlobal to my variable Strompris. Last line also needs to be edited to your scene number (mine is 370)

     

    When you get the price in the variable you just need to fetch in in to a virtual device, I have done some changes and are not really using it like in the first post, so I dont have the virtual device anymore. But you basically just add a label, then use this code in the main loop: 

    local ID = fibaro:getSelfId()

    fibaro:call(ID, "setProperty", "ui.Label1.value", (tonumber(fibaro:getGlobalValue("Strompris"))))

    end

    For the max/min I created a seperate LUA scene to do this calculations, but I'm not using that anymore so I dont have that scene. 

     

    Morten

     

    Edited by mortesan
    Link to comment
    Share on other sites

    • 0
  • Inquirer
  • On 5/24/2018 at 10:33 AM, [email protected] said:

    Interesting. Possible to get a step bye step guide on how to do this?

    I will try to do this when I got some free time. 

    • Like 2
    Link to comment
    Share on other sites

    • 0
    On 5/28/2018 at 7:52 AM, mortesan said:

    I will try to do this when I got some free time. 

     

    Hi,

     

    Would also love to get a step by step description for this!

     

    Kanskje på norsk? Er vel bare i Norge det finnes Tibber?

    Link to comment
    Share on other sites

    • 0

    Hi, 

    Can i "borrow" your Virtual Device and LUA scene to get all the info as shown in your VD?

     

    (Har prøvd masse å få kontakt med Tibber API uten hell før) 

    Mats

    Link to comment
    Share on other sites

    • 0

    Thanks for the script.

    I got this thing working with some minor changes. I've tried to make a short summation here:

     

    Make a global variable in Panels->Variable Panels->Variables called "Strompris", by default it will be 0. Dont mind that.

    Make a LUA-script:

    --[[
    %% properties
    %% events
    %% globals
    --]]


    fibaro:debug(fibaro:getGlobalValue('Strompris'));

    local http = net.HTTPClient();
    http:request('https://api.tibber.com/v1-beta/gql',{
        options = {
          method = 'POST',
          headers = {
            ["Content-Type"] = 'application/json',
            ["Authorization"] = 'Bearer d1007ead2dc84a2b82f0de19451c5fb22112f7ae11d19bf2bedb224a003ff74a'
          },
          data = '{ "query": "{viewer {homes {currentSubscription {priceInfo {current {total energy tax startsAt }}}}}}" }'
        },
       
         success = function(resp)
              if (resp.status == 200) or (resp.status == 201) then           
                  local data = json.decode(resp.data);
                fibaro:debug(resp.data);
                print  ("price: "..tostring(data.data.viewer.homes[2].currentSubscription.priceInfo.current.total));
                 fibaro:setGlobal('Strompris',data.data.viewer.homes[2].currentSubscription.priceInfo.current.total);

              else
                   fibaro:debug(resp.status);
                  fibaro:debug("ERR");

              end
        end,
        error = function(error)
            fibaro:debug"ERROR"
              fibaro:debug(error)
         

        end    
    })

     

    fibaro:sleep (90000);
    fibaro:startScene(51);  --Input Scene number. You can find it on the same page as you insert the script.

     

    Make a virual device.

    Make a Label in the virtal device.

    In the bottom of the advanced header, insert this code. Make sure the name of your Label is "Label1"

    local ID = fibaro:getSelfId(Label1)
    fibaro:call(ID, "setProperty", "ui.Label1.value", (tonumber(fibaro:getGlobalValue("Strompris"))))

     

     

     

     

     

    Link to comment
    Share on other sites

    • 0

    Hi @vegardbr @

    This is great. I've got it working. Thanks for sharing.
    Have one question though, the phone app is showing a different price than what you are getting through Tibber's API. Do you know why?

     

    Link to comment
    Share on other sites

    • 0
    On 1/16/2019 at 1:26 PM, vegardbr said:

    Thanks for the script.

    I got this thing working with some minor changes. I've tried to make a short summation here:

     

    Make a global variable in Panels->Variable Panels->Variables called "Strompris", by default it will be 0. Dont mind that.

    Make a LUA-script:

    --[

     

    Why fatal error? Line 25? Only copy paste the Lua code and made label and virtuel device. Some one? 

    Please login or register to see this attachment.

    Link to comment
    Share on other sites

    • 0

    @vegardbr Takk for scenen!

    Jeg har fulgt oppskriften din i 

    Please login or register to see this link.

     

    og det fungerer supert!!!

     

    Så bra at jeg nå har lyst å hente ut mer fra tibber sin API, f.eks kWh forbrukt siste time osv osv. Jeg har forsøkt å endre på din scene for å hente andre data enn strømpris, men får det ikke til (stadige feilmeldinger).

    Jeg antar det er linjen       data = '{ "query": "{viewer {homes {currentSubscription {priceInfo {current {total energy tax startsAt }}}}}}" }'

    og

     print  ("price: "..tostring(data.data.viewer.homes[2].currentSubscription.priceInfo.current.total));
                 fibaro:setGlobal('Strompris',data.data.viewer.homes[2].currentSubscription.priceInfo.current.total);

    jeg må modifisere, men nøyaktig hvordan?

     

    Fra 

    Please login or register to see this link.

    :

    ønsker jeg å hente f.eks disse verdiene:

    accumulatedConsumptionLastHour

    Please login or register to see this link.

    !

    kWh consumed since since last hour shift

     

     

    Setter stor pris på om du kan hjelpe meg her :-)

     

    Link to comment
    Share on other sites

    • 0

    @Boxer72 Har du kommet noe videre på tanken din?
    Kan se for meg noe lignende, da jeg ønsker hente faktisk forbruk og kostnad på en enhet, for å regne ut forbruk på elbil ladding til leieboer.


    Fikk du til pristabell? Skal "Pristabell" være synlig med noe data inne på Predefined variables? 

    Står foreløpig bare Value 1 hos meg, selv etter å ha kjørt de linjene 14-18 for å definere tabell første gangen.

     

    Kan da heller ikke se noe endring på Variabel: Dyrstrom

    EDIT: Ser nå at tabellen kommer opp inne på scenen under Advanced på både Pristabell og resultat ved endring på Dyrstrøm.
    Skulle gjerne funnet ut om de kan kobles mer mot for bruk og regnestykke er opp mot enkeltenheter.

    Edited by dorten75
    Link to comment
    Share on other sites

    • 0
    On 1/16/2019 at 1:26 PM, vegardbr said:

    --[[
    %% properties
    %% events
    %% globals
    --]]


    fibaro:debug(fibaro:getGlobalValue('Strompris'));

    local http = net.HTTPClient();
    http:request('https://api.tibber.com/v1-beta/gql',{
        options = {
          method = 'POST',
          headers = {
            ["Content-Type"] = 'application/json',
            ["Authorization"] = 'Bearer d1007ead2dc84a2b82f0de19451c5fb22112f7ae11d19bf2bedb224a003ff74a'
          },
          data = '{ "query": "{viewer {homes {currentSubscription {priceInfo {current {total energy tax startsAt }}}}}}" }'
        },
       
         success = function(resp)
              if (resp.status == 200) or (resp.status == 201) then           
                  local data = json.decode(resp.data);
                fibaro:debug(resp.data);
                print  ("price: "..tostring(data.data.viewer.homes[2].currentSubscription.priceInfo.current.total));
                 fibaro:setGlobal('Strompris',data.data.viewer.homes[2].currentSubscription.priceInfo.current.total);

              else
                   fibaro:debug(resp.status);
                  fibaro:debug("ERR");

              end
        end,
        error = function(error)
            fibaro:debug"ERROR"
              fibaro:debug(error)
         

        end    
    })

     

    fibaro:sleep (90000);
    fibaro:startScene(51);

     

    Hei. Jeg får kun ut "0" av denne. Hva har jeg ikke fått med meg? :)

     

    Link to comment
    Share on other sites

    • 0
    On 10/3/2019 at 9:56 PM, julusmoen said:

     

    Why fatal error? Line 25? Only copy paste the Lua code and made label and virtuel device. Some one? 

    Please login or register to see this attachment.

     

    "data.data.viewer.homes[x]"  is a list, and which row you want depends on how many homes you have registerd to your tibber profile. 

    Most prople probably have only one, so use '1' in this field. 

    fibaro:setGlobal('Strompris',data.data.viewer.homes[1].currentSubscription.priceInfo.current.total);

    Link to comment
    Share on other sites

    • 0

    I have made an HC3 integration for getting all spot prices from tibber:

     

    --By Odd Reidar Vegsund 29.12.2021
    local urlApi = "https://api.tibber.com/v1-beta/gql"
    local Token = "d1007ead2dc84a2b82f0de19451c5fb22112f7ae11d19bf2bedb224a003ff74a"
    local tcpTimeout = 3000
     
    --https://developer.tibber.com/explorer 
    local Quary = '{viewer{homes{currentSubscription{priceInfo{current{total energy tax startsAt}today{total energy tax startsAt}tomorrow{total energy tax startsAt}}}}}}'
     
    print("Get spotprice info from tibber started")
     
    --http://json2table.com/ to see structure
    function ReadJson(apiResult)
        print("ReadJson startet.")
        jsonTable = json.decode(apiResult)
     
        local PricesToday = jsonTable.data.viewer.homes[1].currentSubscription.priceInfo.today -- Get the table for today
        local PricesTomorrow = jsonTable.data.viewer.homes[1].currentSubscription.priceInfo.tomorrow  -- Get the table for tomorrow
        print("PricesToday Total: " .. PricesToday[1].total)  --@ 00:00, you can use .total .energy .tax .startsAt
        print("PricesToday Total: " .. PricesToday[24].total)  --@ 23:00
     
       -- fibaro.setGlobalVariable('StromSpotPris00OrekWh', PricesToday[1].total) --To set the global variabel
     
        print("PricesTomorrow Total: " .. PricesTomorrow[1].total)  --@ 00:00
        print("PricesTomorrow Total: " .. PricesTomorrow[24].total)  --@ 23:00
     
        --If you want to loop
        for k, v in pairs(PricesToday) do -- for every key in the table with a corresponding non-nil value
           --print(PricesToday[k].total)
        end
     
        --If you want to loop
        for k, v in pairs(PricesTomorrow) do -- for every key in the table with a corresponding non-nil value
           --print(PricesTomorrow[k].total)
        end
     
         print("ReadJson compleated.")
    end
     
    function GetJson(UrlInn)
        net.HTTPClient():request(UrlInn, {
                    options={
                    method = 'POST',
                     headers = {
                        ["Content-Type"] = 'application/json',
                        ["Authorization"] = 'Bearer ' .. Token
                    },
                    data = '{ "query": "' .. Quary .. '" }',
                    timeout = tcpTimeout,
                    checkCertificate = true
                    },
                    success = function(response) 
                            --print(response.data)
                            ReadJson(response.data)
                    end,
                    error = function(message)
                            print("Error:", message)
                    end
                }) 
    end
     
    GetJson(urlApi) 
    • Like 1
    Link to comment
    Share on other sites

    • 0
    On 12/29/2021 at 4:38 PM, SmartHomeEddy said:

    I was 40 minutes earlier :-) 

     

     

    This app is great, but it is missing integration with livedata from Tibber Puls. Have anyone added that connection ? I can seem to get it to work.  Here is a Python script from tibber: 

    Please login or register to see this code.

    Guides

    Please login or register to see this link.

    Please login or register to see this link.

     

     

    Link to comment
    Share on other sites

    • 0
    10 hours ago, Alexander_k_r said:

    This app is great, but it is missing integration with livedata from Tibber Puls. Have anyone added that connection ? I can seem to get it to work. 


    Live measurements are possible with Fibaro WebSocket, but is a bit more complicated ?

    Link to comment
    Share on other sites

    • 0
    On 12/29/2021 at 4:29 PM, Oddi_78 said:

    Jag har gjort en HC3-integration för att få alla spotpriser från tibber:

     

    --Av Odd Reidar Vegsund 29.12.2021
    lokal  urlApi =  "https://api.tibber.com/v1-beta/gql"
    lokal  token =  "d1007ead2dc84a2b82f0de19451c5fb22112f7ae11d19bf2bedb224a003ff74a"
    lokal  tcpTimeout =  3000
     
    --https://developer.tibber.com/explorer 
    local  Quary =  '{betraktare{hem{nuvarande Prenumeration{prisInfo{nuvarande{total energiskatt startarAt}idag{total energiskatt startarImorgon{total energiskatt startarAt}}}}}}'
     
    print( "Hämta spotprisinformation från tibber started" )
     
    --http://json2table.com/ för att se struktur
    funktion  ReadJson(apiResult)
        print( "ReadJson startade." )
        jsonTable = json.decode(apiResult)
     
        local  PricesToday = jsonTable.data.viewer.homes[ 1 ].currentSubscription.priceInfo.today  -- Skaffa tabellen för idag
        local  PricesTomorrow = jsonTable.data.viewer.homes[ 1 ].currentSubscription.priceInfo.tomorrow   -- Få bordet för imorgon
        print( "PricesToday Total: "  .. PricesToday[ 1 ].total)   --@  00:00, du kan använda .total .energy .tax .startsAt
        print( "PricesToday Total: "  .. PricesToday[ 24 ].total)   --@  23:00
     
       -- fibaro.setGlobalVariable('StromSpotPris00OrekWh', PricesToday[1].total) --För att ställa in den globala variabeln
     
        print( "PricesTomorrow Total: "  .. PricesTomorrow[ 1 ].total)   --@  00:00
        print( "PricesTomorrow Total: "  .. PricesTomorrow[ 24 ].total)   --@  23:00
     
        --Om du vill loopa
        för  k, v  i  par(PricesToday)  gör -- för varje nyckel i tabellen med ett motsvarande värde som inte är noll 
           --print(PricesToday[k].total)
        slutet
     
        --Om du vill loopa
        för  k, v  i  par(PricesTomorrow)  gör -- för varje nyckel i tabellen med ett motsvarande värde som inte är noll 
           --print(PricesTomorrow[k].total)
        slutet
     
         print( "ReadJson compleated." )
    slutet
     
    funktion  GetJson(UrlInn)
        net.HTTPClient():request(UrlInn, {
                    alternativ={
                    metod =  'POST' ,
                     rubriker = {
                        [ "Content-Type" ] =  'applikation/json' ,
                        [ "Authorization" ] =  'Bärare'  .. Token
                    },
                    data =  '{ "query": "'  .. Quary ..  '" }' ,
                    timeout = tcpTimeout,
                    checkCertificate =  sant
                    },
                    framgång =  funktion (svar) 
                            --print(response.data)
                            ReadJson(response.data)
                    slut ,
                    fel =  funktion (meddelande)
                            print( "Fel:" , meddelande)
                    slutet
                }) 
    slutet
     
    GetJson(urlApi) 

    Hello
    This works great.
    What should I do to get the average price?

    Maybe it is possible to find the 5 lowest prices for running the geothermal heat pump at that time?

    is it possible to convert the table to clock time instead and start the geothermal heat pump after that?

    Regards Peter

    Edited by PeterM5
    Add question.
    Link to comment
    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...