Giter VIP home page Giter VIP logo

pytibber's Introduction

pyTibber

PyPI version Code style: black License: MIT

Python3 library for Tibber.

Get electricity price and consumption.

If you have a Tibber Pulse or Watty you can see your consumption in real time.

Buy me a coffee :)

Go to developer.tibber.com/ to get your API token.

Install

pip3 install pyTibber

Example:

import tibber.const
import tibber
import asyncio


async def start():
  tibber_connection = tibber.Tibber(tibber.const.DEMO_TOKEN, user_agent="change_this")
  await tibber_connection.update_info()
  print(tibber_connection.name)

  home = tibber_connection.get_homes()[0]
  await home.fetch_consumption_data()
  await home.update_info()
  print(home.address1)

  await home.update_price_info()
  print(home.current_price_info)
  
  # await tibber_connection.close_connection()

loop = asyncio.run(start())

Example realtime data:

An example of how to subscribe to realtime data (Pulse/Watty):

import tibber.const
import asyncio

import aiohttp
import tibber

def _callback(pkg):
    print(pkg)
    data = pkg.get("data")
    if data is None:
        return
    print(data.get("liveMeasurement"))


async def run():
    async with aiohttp.ClientSession() as session:
        tibber_connection = tibber.Tibber(tibber.const.DEMO_TOKEN, websession=session, user_agent="change_this")
        await tibber_connection.update_info()
    home = tibber_connection.get_homes()[0]
    await home.rt_subscribe(_callback)    

    while True:
      await asyncio.sleep(10)

loop = asyncio.run(run())

The library is used as part of Home Assistant.

pytibber's People

Contributors

bdraco avatar beatsudev avatar danielhiversen avatar dependabot-preview[bot] avatar erijo avatar gunnarbjoru avatar haugene avatar kaar avatar knodd avatar konkrog avatar lgtm-com[bot] avatar magnusnordlander avatar mnorrsken avatar toini avatar ztamas83 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pytibber's Issues

Question

Trying to run in pycharm, pytibber module loaded

Where should I put my access_token?
import tibber
tibber_connection = tibber.Tibber() # access_token=YOUR_TOKEN
tibber_connection.sync_update_info()

How should this look?
import tibber
tibber_connection = tibber.Tibber()
access_token='1314123123xxxxx' # like this? I still get Arya Stark when using this
tibber_connection.sync_update_info()

Step by step guide

Hi Daniel and thanks for this awesome repo!
Do you have any plans to add a "step-by-step" guide or a short youtube video on how to run this?

Regards
Lamin

list index out of range in realtime example

Hello!

When I try the realtime-example with my own access_token I got a "IndexError: list index out of range" on "home = tibber_connection.get_homes()[0]"

Could it be because I don't have a contract with Tibber? I only have a "pulse" so far and in the API explorer the realtime-subscription works. Or do I have to enter something of my own in the "user agent"? (I had actually tried...)

With the demo token no error comes - but of course also no data

"Fatal Python error: Segmentation fault" from a Raspberry Pi Python3.9.3 32-bit

Trace below after adding import faulthandler; faulthandler.enable() according to https://blog.richard.do/2018/03/18/how-to-debug-segmentation-fault-in-python/

`pi@raspberrypi:~/dev/EnergyMeterTelemetry $ python -Xfaulthandler TibberClient.py
Fatal Python error: Segmentation fault

Thread 0xb5604460 (most recent call first):
File "/usr/local/opt/python-3.9.3/lib/python3.9/concurrent/futures/thread.py", line 75 in _worker
File "/usr/local/opt/python-3.9.3/lib/python3.9/threading.py", line 892 in run
File "/usr/local/opt/python-3.9.3/lib/python3.9/threading.py", line 954 in _bootstrap_inner
File "/usr/local/opt/python-3.9.3/lib/python3.9/threading.py", line 912 in _bootstrap

Current thread 0xb6f8f010 (most recent call first):
File "/home/pi/.local/lib/python3.9/site-packages/aiohttp/client_proto.py", line 213 in data_received
File "/usr/local/opt/python-3.9.3/lib/python3.9/asyncio/sslproto.py", line 545 in data_received
File "/usr/local/opt/python-3.9.3/lib/python3.9/asyncio/selector_events.py", line 870 in _read_ready__data_received
File "/usr/local/opt/python-3.9.3/lib/python3.9/asyncio/selector_events.py", line 813 in _read_ready
File "/usr/local/opt/python-3.9.3/lib/python3.9/asyncio/events.py", line 80 in _run
File "/usr/local/opt/python-3.9.3/lib/python3.9/asyncio/base_events.py", line 1890 in _run_once
File "/usr/local/opt/python-3.9.3/lib/python3.9/asyncio/base_events.py", line 596 in run_forever
File "/usr/local/opt/python-3.9.3/lib/python3.9/asyncio/base_events.py", line 629 in run_until_complete
File "/home/pi/.local/lib/python3.9/site-packages/tibber/init.py", line 131 in sync_update_info
File "/home/pi/dev/EnergyMeterTelemetry/TibberClient.py", line 8 in
Segmentation fault`

Demo code works on my Ubuntu Python 3.8.10 64-bit.

Any suggestions?

Hardcoded offpeak

Offpeak is hard coded in code to 20:00 - 08:00 in current_attributes (unless I misread the code), probably should be configurable settings somehow as at least in Norway we will get 22:00 - 06:00 as off peak? (Nye nettleien som er litt utsatt).

Mvh
Morten

Away state from Tibber app

I'd like to use the Tibber app to set the "away state" of my home, and then use this flag in Home Assistant to control other components in the house. As far as I can tell this is not exposed in the Tibber API, but you might know of a way to expose this?

If it could be implemented in the home assistant plugin it would be great :)

Add Consumtion endpoint

Hi,

Are there any plans for adding the consumption endpoint in the Tibber API to this library?

It would be nice to view the consumtion in the Home Assistant even without a real time device.

{
  viewer {
    homes {
      consumption(resolution: HOURLY, last: 100) {
        nodes {
           ...
        }
      }
    }
  }
}

Example apparently does not work

Hi,

The example "Example realtime data:" seems not to work and is not complete. I added:

asyncio.run(run()), and got an exception "Please provide value for HTTP user agent....."

Best regards,
Carl.

Error

Hi,

Do you know why I get these errors?

Using legacy 'setup.py install' for pyTibber, since package 'wheel' is not installed.
Using legacy 'setup.py install' for graphql-subscription-manager, since package 'wheel' is not installed.
Using legacy 'setup.py install' for websockets, since package 'wheel' is not installed.
Building wheels for collected packages: multidict, yarl
  Building wheel for multidict (PEP 517) ...  \ | / - error
  ERROR: Command errored out with exit status 1:
   command: /opt/bin/python3 /opt/lib/python3.8/site-packages/pip/_vendor/pep517/_in_process.py build_wheel /tmp/tmp_p4obwqh
       cwd: /tmp/pip-install-uex99r6d/multidict_ca48e499e60548f9ab4be4443def495f
  Complete output (47 lines):
  *********************
  * Accelerated build *
  *********************
  running bdist_wheel
  running build
  running build_py
  creating build
  creating build/lib.linux-armv7l-3.8
  creating build/lib.linux-armv7l-3.8/multidict
  copying multidict/_multidict_py.py -> build/lib.linux-armv7l-3.8/multidict
  copying multidict/_multidict_base.py -> build/lib.linux-armv7l-3.8/multidict
  copying multidict/_compat.py -> build/lib.linux-armv7l-3.8/multidict
  copying multidict/_abc.py -> build/lib.linux-armv7l-3.8/multidict
  copying multidict/init.py -> build/lib.linux-armv7l-3.8/multidict
  running egg_info
  writing multidict.egg-info/PKG-INFO
  writing dependency_links to multidict.egg-info/dependency_links.txt
  writing top-level names to multidict.egg-info/top_level.txt
  reading manifest file 'multidict.egg-info/SOURCES.txt'
  reading manifest template 'MANIFEST.in'
  warning: no previously-included files matching '.pyc' found anywhere in distribution
  warning: no previously-included files found matching 'multidict/_multidict.html'
  warning: no previously-included files found matching 'multidict/
.so'
  warning: no previously-included files found matching 'multidict/.pyd'
  warning: no previously-included files found matching 'multidict/
.pyd'
  no previously-included directories found matching 'docs/_build'
  writing manifest file 'multidict.egg-info/SOURCES.txt'
  copying multidict/init.pyi -> build/lib.linux-armv7l-3.8/multidict
  copying multidict/_multidict.c -> build/lib.linux-armv7l-3.8/multidict
  copying multidict/py.typed -> build/lib.linux-armv7l-3.8/multidict
  creating build/lib.linux-armv7l-3.8/multidict/_multilib
  copying multidict/_multilib/defs.h -> build/lib.linux-armv7l-3.8/multidict/_multilib
  copying multidict/_multilib/dict.h -> build/lib.linux-armv7l-3.8/multidict/_multilib
  copying multidict/_multilib/istr.h -> build/lib.linux-armv7l-3.8/multidict/_multilib
  copying multidict/_multilib/iter.h -> build/lib.linux-armv7l-3.8/multidict/_multilib
  copying multidict/_multilib/pair_list.h -> build/lib.linux-armv7l-3.8/multidict/_multilib
  copying multidict/_multilib/views.h -> build/lib.linux-armv7l-3.8/multidict/_multilib
  running build_ext
  building 'multidict._multidict' extension
  creating build/temp.linux-armv7l-3.8
  creating build/temp.linux-armv7l-3.8/multidict
  arm-openwrt-linux-gnueabi-gcc -Wno-unused-result -Wsign-compare -DNDEBUG -O2 -pipe -mtune=cortex-a9 -fno-caller-saves -fhonour-copts -Wno-error=unused-but-set-variable -Wno-error=unused-result -mfloat-abi=soft -O2 -pipe -mtune=cortex-a9 -fno-caller-saves -fhonour-copts -Wno-error=unused-but-set-variable -Wno-error=unused-result -mfloat-abi=soft -DNDEBUG -fno-inline -pthread -O2 -pipe -mtune=cortex-a9 -fno-caller-saves -fhonour-copts -Wno-error=unused-but-set-variable -Wno-error=unused-result -mfloat-abi=soft -DNDEBUG -fno-inline -pthread -I/work/stable/Entware/staging_dir/target-arm_cortex-a9_glibc-2.23_eabi/opt/include -I/work/stable/Entware/staging_dir/toolchain-arm_cortex-a9_gcc-8.3.0_glibc-2.23_eabi/include -fPIC -I/opt/include/python3.8 -c multidict/_multidict.c -o build/temp.linux-armv7l-3.8/multidict/_multidict.o -O2 -std=c99 -Wall -Wsign-compare -Wconversion -fno-strict-aliasing -pedantic
  multidict/_multidict.c:1:10: fatal error: Python.h: No such file or directory
   #include "Python.h"
            ^~~~~~~~~~
  compilation terminated.
  error: command 'arm-openwrt-linux-gnueabi-gcc' failed with exit status 1
  ----------------------------------------
  ERROR: Failed building wheel for multidict
 \ | / error
  ERROR: Command errored out with exit status 1:
   command: /opt/bin/python3 /opt/lib/python3.8/site-packages/pip/_vendor/pep517/_in_process.py build_wheel /tmp/tmpyv2fugb1
       cwd: /tmp/pip-install-uex99r6d/yarl_591db27366ba4babadb1e5a2d55fca52
  Complete output (42 lines):
  **********************
  * Accellerated build *
  **********************
  running bdist_wheel
  running build
  running build_py
  creating build
  creating build/lib.linux-armv7l-3.8
  creating build/lib.linux-armv7l-3.8/yarl
  copying yarl/_url.py -> build/lib.linux-armv7l-3.8/yarl
  copying yarl/_quoting_py.py -> build/lib.linux-armv7l-3.8/yarl
  copying yarl/_quoting.py -> build/lib.linux-armv7l-3.8/yarl
  copying yarl/init.py -> build/lib.linux-armv7l-3.8/yarl
  running egg_info
  writing yarl.egg-info/PKG-INFO
  writing dependency_links to yarl.egg-info/dependency_links.txt
  writing requirements to yarl.egg-info/requires.txt
  writing top-level names to yarl.egg-info/top_level.txt
  reading manifest file 'yarl.egg-info/SOURCES.txt'
  reading manifest template 'MANIFEST.in'
  warning: no previously-included files matching '.pyc' found anywhere in distribution
  warning: no previously-included files matching '
.cache' found anywhere in distribution
  warning: no previously-included files found matching 'yarl/.html'
  warning: no previously-included files found matching 'yarl/
.so'
  warning: no previously-included files found matching 'yarl/*.pyd'
  no previously-included directories found matching 'docs/_build'
  writing manifest file 'yarl.egg-info/SOURCES.txt'
  copying yarl/init.pyi -> build/lib.linux-armv7l-3.8/yarl
  copying yarl/_quoting_c.c -> build/lib.linux-armv7l-3.8/yarl
  copying yarl/_quoting_c.pyi -> build/lib.linux-armv7l-3.8/yarl
  copying yarl/_quoting_c.pyx -> build/lib.linux-armv7l-3.8/yarl
  copying yarl/py.typed -> build/lib.linux-armv7l-3.8/yarl
  running build_ext
  building 'yarl._quoting_c' extension
  creating build/temp.linux-armv7l-3.8
  creating build/temp.linux-armv7l-3.8/yarl
  arm-openwrt-linux-gnueabi-gcc -Wno-unused-result -Wsign-compare -DNDEBUG -O2 -pipe -mtune=cortex-a9 -fno-caller-saves -fhonour-copts -Wno-error=unused-but-set-variable -Wno-error=unused-result -mfloat-abi=soft -O2 -pipe -mtune=cortex-a9 -fno-caller-saves -fhonour-copts -Wno-error=unused-but-set-variable -Wno-error=unused-result -mfloat-abi=soft -DNDEBUG -fno-inline -pthread -O2 -pipe -mtune=cortex-a9 -fno-caller-saves -fhonour-copts -Wno-error=unused-but-set-variable -Wno-error=unused-result -mfloat-abi=soft -DNDEBUG -fno-inline -pthread -I/work/stable/Entware/staging_dir/target-arm_cortex-a9_glibc-2.23_eabi/opt/include -I/work/stable/Entware/staging_dir/toolchain-arm_cortex-a9_gcc-8.3.0_glibc-2.23_eabi/include -fPIC -I/opt/include/python3.8 -c yarl/_quoting_c.c -o build/temp.linux-armv7l-3.8/yarl/_quoting_c.o
  yarl/_quoting_c.c:4:10: fatal error: Python.h: No such file or directory
   #include "Python.h"
            ^~~~~~~~~~
  compilation terminated.
  error: command 'arm-openwrt-linux-gnueabi-gcc' failed with exit status 1
  ----------------------------------------
  ERROR: Failed building wheel for yarl
ERROR: Could not build wheels for multidict, yarl which use PEP 517 and cannot be installed directly

root@R6250:/tmp/home/root# python3
Python 3.8.1 (default, Mar 23 2020, 07:23:17) 
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.

 import tibber
Traceback (most recent call last):
  File "", line 1, in 
ModuleNotFoundError: No module named 'tibber'

Endpoint for sending car battery status

I use Home Assistant, have an Easee charger, but, unfortunately, a Nissan Leaf. This car is not supported for integration towards Tibber and, hence, the smart charging functionality isn't very smart. Could we use this library to send car battery status updates to Tibber? If so, we could allow Home assistant to send battery updates and thereby allow for an arbitrary car integration?

Or, perhaps, we could get access to the algorithm and the smartcharging ourselves :-)

Excessive logging from gql

Hi.

I just upgraded to Home Assistant 2022.12, and it seems the usage of gql in #222 introduced some excessive info-logging of every websocket-payload. It spammed my log heavily, so I had to add a "gql.transport.websockets: warning" to my logger-setup.

Might be some inherited log.isEnabledFor(logging.INFO) somewhere.

The version of gql installed by default in Home Assistant Container (docker) is:
bash-5.1# pip show gql
Name: gql
Version: 3.4.0

Best regards
Heikki

Issues with tibber in home assistant

Hi. Maybe not right issue tracker, but I am having trouble with tibber component/sensor in home assistant. Sometimes it works, sometimes it does not and displays please check your config even though nothing has changed.

Logs look like this:

2018-11-26 20:20:59 INFO (MainThread) [homeassistant.loader] Loaded tibber from homeassistant.components.tibber
2018-11-26 20:20:59 INFO (MainThread) [homeassistant.setup] Setting up tibber
2018-11-26 20:21:02 INFO (MainThread) [homeassistant.loader] Loaded sensor.tibber from homeassistant.components.sensor.tibber
2018-11-26 20:21:13 WARNING (MainThread) [homeassistant.setup] Setup of tibber is taking over 10 seconds.
2018-11-26 20:21:13 INFO (MainThread) [homeassistant.components.sensor] Setting up sensor.tibber
2018-11-26 20:21:13 ERROR (MainThread) [tibber] Error connecting to Tibber:
2018-11-26 20:21:13 INFO (MainThread) [homeassistant.setup] Setup of domain tibber took 13.5 seconds.
2018-11-26 20:21:13 ERROR (MainThread) [homeassistant.setup] Setup failed for tibber: Component failed to initialize.
2018-11-26 20:21:13 ERROR (MainThread) [homeassistant.components.sensor.tibber] Tibber sensor configuration has changed. Check https://home-assistant.io/components/tibber/

This is running HA 0.82.1. I have verified that the access token is valid and as mentioned it works on and off..

Any help would be appreciated

Found less data than requested

From tibber_home.get_historic_data I get the warning "Found less data than requested".
I tried to understand the code, but I don't understand the role of "max_n_data = max_n_data // 10" in the loop.
It starts with 5000, then 500, 50, 5 and 0.
Also, the API returns the hierarchy viewer->homes->comsumption and not viewer->home->consumption, but maybe this is due to the fact that this integration uses the old API.

python3.6.9 SyntaxError

When testing the code it raises SyntaxError

$ python3
Python 3.6.9 (default, Dec  8 2021, 21:08:43)
[GCC 8.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import tibber
>>> access_token = tibber.DEMO_TOKEN
>>> tibber_connection = tibber.Tibber(access_token)
>>> await tibber_connection.update_info()
  File "<stdin>", line 1
    await tibber_connection.update_info()
                          ^
SyntaxError: invalid syntax

Sysinfo:

uname -a
Linux 5.4.0-91-generic #102~18.04.1-Ubuntu SMP Thu Nov 11 14:46:36 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux

Peak and offpeak

What is the intended purpose of the attributes peak, offpeak_1 and offpeak_2?

Adding prices by hour

Any chance of adding the prices of today and to tomorrow to the sensor in HomeAssistant, today I´m fetching them via an rest sensor, and then displaying them in an custom Lovelace chart card.

The Restsensor set up looks like this today

 - platform: rest
    name: Tibber Price
    resource: https://api.tibber.com/v1-beta/gql
    method: POST
    payload: '{ "query": "{viewer {homes {currentSubscription {priceInfo {today {total} tomorrow {total}}}}}}"}'
    headers:
      Authorization: "Bearer <token>"
      User-Agent: Home Assistant
      Content-Type: application/json
    json_attributes_path: "$.data.viewer.homes[0].currentSubscription.priceInfo"
    json_attributes:
      - today
      - tomorrow
    scan_interval: 14400
    value_template: 'OK'

And then I display it in my custom lovelace card found here https://github.com/angoyd/hass-things/tree/main/tibber-card.

But it would have been nice not to have to setup an extra rest sensor to get the prices over the day, also its and extra call for the tibber api.

Error on bad connection makes HA stops pulling

Here's the error log.

2022-10-10 01:23:50.760 INFO (MainThread) [homeassistant.setup] Setting up tibber
2022-10-10 01:23:50.760 INFO (MainThread) [homeassistant.setup] Setup of domain tibber took 0.0 seconds
2022-10-10 01:24:02.169 ERROR (MainThread) [tibber] Timed out when connecting to Tibber <--- I always get this one even when it works
2022-10-10 01:24:02.174 WARNING (MainThread) [homeassistant.config_entries] Config entry 'klem' for tibber integration not ready yet; Retrying in background <--- I always get this one even when it works
2022-10-10 01:24:27.356 INFO (MainThread) [homeassistant.components.sensor] Setting up sensor.tibber
2022-10-10 01:24:32.111 ERROR (MainThread) [homeassistant.components.sensor] tibber: Error on device update!
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/entity_platform.py", line 493, in _async_add_entity
    await entity.async_device_update(warning=False)
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 703, in async_device_update
    await task
  File "/usr/src/homeassistant/homeassistant/components/tibber/sensor.py", line 373, in async_update
    res = self._tibber_home.current_price_data()
  File "/usr/local/lib/python3.10/site-packages/tibber/tibber_home.py", line 368, in current_price_data
    return round(self.price_total[key], 3), self.price_level[key], price_time
KeyError: '2022-10-09T23:00:00.000+02:00'
2022-10-10 01:24:37.361 WARNING (MainThread) [homeassistant.components.sensor] Setup of sensor platform tibber is taking over 10 seconds.
2022-10-10 01:24:39.120 ERROR (MainThread) [homeassistant.components.sensor] tibber: Error on device update!
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/entity_platform.py", line 493, in _async_add_entity
    await entity.async_device_update(warning=False)
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 703, in async_device_update
    await task
  File "/usr/src/homeassistant/homeassistant/components/tibber/sensor.py", line 373, in async_update
    res = self._tibber_home.current_price_data()
  File "/usr/local/lib/python3.10/site-packages/tibber/tibber_home.py", line 368, in current_price_data
    return round(self.price_total[key], 3), self.price_level[key], price_time
KeyError: '2022-10-09T23:00:00.000+02:00'
2022-10-10 01:24:39.159 INFO (MainThread) [homeassistant.components.notify] Setting up notify.tibber

Dependabot can't evaluate your Python dependency files

Dependabot can't evaluate your Python dependency files.

As a result, Dependabot couldn't check whether any of your dependencies are out-of-date.

The error Dependabot encountered was:

InstallationError("Invalid requirement: 'The MIT License (MIT)'\n",)

You can mention @dependabot in the comments below to contact the Dependabot team.

AttributeError: 'Client' object has no attribute 'session'

Hi, I don't get rt_subsctibe to work with a fresh ubuntu docker container with pytibber and run the example code for realtime data. The problem seems to be related to the use of gql.client in this line of tibber_home.py:

async for data in self._tibber_control.sub_manager.session.subscribe(

When I catch the exception thrown here I get the message:

AttributeError: 'Client' object has no attribute 'session'

Whis seems to be correct. gql.client does not have a "session", but does have a "subscribe".

So, when I tried to fix the code to the following line:

async for data in self._tibber_control.sub_manager.subscribe( # Removed .session.

I got this exception:

'async for' requires an object with __aiter__ method, got generator so I might be wrong with my assumptions.

So, is pyTibber dependent on a spesific/older version of gql since it uses .session? Or is the .session attribute generated when a successfull connection is established?

Including energy consumption in update_info()

For user like me without access to real-time electricity consumption data, it's still useful to access the consumption data that the API provides out of the box. In turn, this will allow the Home Assistant sensor to be able to query and use these values.

Therefore I would suggest including the following lines after line #297 in __init__.py in the update_info() function. Sorry, I'm not good with git otherwise I'd do a pull request.

         consumption(resolution: DAILY, last: 1) {
           nodes {
             from
             to
             consumption
             consumptionUnit
             unitPrice
             unitPriceVAT
             cost
             totalCost
             currency
           }
         }

Unfortunately, data are only provided only up till yesterday -- limited by Tibber. And even then, it's still not the most elegant solution, as ideally it would only need to query this once per day not every update cycle. But it does work fine at least for me and it's better than nothing...

The sensor.py in your Home Assistant Tibber component can then have the following lines added at the end of the async_update() function to display these values in the attributes.

This is probably not at all useful for people who do have real-time data. I can't judge that, but in that case you may wish to start this block with a condition if not home.has_real_time_consumption:

   try:
       await self._tibber_home.update_info()
   except (asyncio.TimeoutError, aiohttp.ClientError):
       return
   data = self._tibber_home.info["viewer"]["home"]
   self._device_state_attributes["grid_company"] = data["meteringPointData"]["gridCompany"]
   self._device_state_attributes["grid_company_production"] = data["meteringPointData"]["estimatedAnnualConsumption"]
   daily_consumption_data = data["consumption"]["nodes"][0]
   self._device_state_attributes["consumption_yesterday_" + str(daily_consumption_data["consumptionUnit"])] = daily_consumption_data["consumption"]
   self._device_state_attributes["consumption_yesterday_" + str(daily_consumption_data["currency"])] = round( daily_consumption_data["consumption"] * ( daily_consumption_data["unitPrice"] + daily_consumption_data["unitPriceVAT"]), 3 )

image

No home?

Hi

I have 2 homes (at work) connected to my API key. When I use https://developer.tibber.com/explorer? -
{
viewer {
homes {
address {
address1
address2
address3
postalCode
city
country
latitude
longitude
}
}
}
}

both homes is listed. But, when I us this one self.tibber_connection.get_homes(), I get a len(): 0

If I use my personal API key, I get len(): 2 (correct - I have 2 homes related to Tibber).

So, why is one key working, and not the other one. But there is no difference when I use the grahpiQL?

All pytest tests in the code-checker workflow are skipped because pytest-asyncio is not installed.

Async tests marked with the @pytest.mark.asyncio decorator are skipped because no asyncio pytest library is installed for the workflow. See https://github.com/Danielhiversen/pyTibber/runs/5961849621?check_suite_focus=true#step:9:61.

Pytest-asyncio should be added as a dependency in the workflow. I've done this in the commit: d99cb9a, however, this introduces a new issue with the cache action where the setup job part fails (see https://github.com/Danielhiversen/pyTibber/runs/6702463399?check_suite_focus=true). The @actions/setup-python action uses @actions/cache under the hood, so I think the @actions/cache step can be removed completely in favour of setup-python (see https://github.com/actions/setup-python#caching-packages-dependencies).

Undocumented websockets dependency

It seems like pyTibber has an undocumented dependency to websockets.
Noticed when running in a fresh Docker container setup.

I'm not sure where dependencies are stored, so I hesitated making a PR :/

pyTibber uses disabled websocket API

Hi Daniel,

during testing I discovered that this library does not use the new API. As of developer.tibber.com, the old websocket api has been switched off as of 4 january 14:00.

Please let me know if that oberservation is right. See also my remark at #240 (comment)

Br
Carl.

await' outside function

First - thank you for a great contribution to python and HA! Love it!

Second - I realize that this is not an issue, more a complex feature request / discussion across HA and this library?

I want to use the day-a-head pricing from Tibber to optimize the heating of my cabin (to keep it free of frost) during the winter. Specifically, it turns out that heating the cabin at night can save a lot of money by avoiding peak-pricing.

It does however turn out that there are signficant day-to-day variations, and as such I need to tailor the heating to the specific pricing for each day. So I want to pull the day-a-head in the evening. Ideally this would be a attribute in Home Assistant that I could pass on to a python script. I don't know how that would look as an attribute? Perhaps an array for hours 0-23?

My alternative is to pull the data myself directly in the python script. Trying to run the example in a simple script I get this feedback:
SyntaxError: 'await' outside function

I realize that this is probably to the lack of async, and I am not a very experienced programmer (have contributed to HA though :)). But is it possible to use the library synchronously to pull the day-a-head once?

[Feature equest] Add statistics for the cost/energy to be used in the HA energy dashboard

Not sure if this is supported in pyTibber aleady or maybe it should be implemented in HA directly,

Today we have the this for the tibber integration in home assistant(HA)

Once a day a statistics with hourly consumption and cost data is generated that can be used in the Energy Dashboard. (The ids are tibber:energy_consumption_HOMEID and tibber:energy_totalcost_HOMEID )

It would be nice to see the "cost/money per kWh" that day/week/month and so on.
Today the tibber:energy_totalcost_HOMEID includes the monthly fee. Maybe this can be discussed if it should be included in this statistic or not.

It could look something like this maybe:
1afdbc3140ecf29ef524b39a43714f91b2d6972e
When looking at the energy dashboard in HA

Include Price.tax

In order to calculate the complete price including grid costs etc, I would like the Tibber integration to Home Assistant to include the tax part of the electricity price. Since the price of guarantee of origin certificate appears to vary unpredictably, it would be very useful to be able to pick the current value from the Tibber API..

aiohttp.client_exceptions.ClientConnectorError

Hi,
I am running pytibber version o. on docker with python:3.9-slim-buster (Python 3.9.13).
My requirements.txt file has:
aiohttp==3.8.1
aiosignal==1.2.0
async-timeout==4.0.2
attrs==22.1.0
charset-normalizer==2.1.0
frozenlist==1.3.0
graphql-subscription-manager==0.4.3
idna==3.3
multidict==6.0.2
numpy==1.23.1
pandas==1.4.3
psycopg2==2.9.3
python-dateutil==2.8.2
pyTibber
boto3 >= 1.20.13
argparse
AWSIoTPythonSDK==1.5.2

The code is the same you propose as example:
_async def main():
access_token = ACCESS_TOKEN
tibber_connection = tibber.Tibber(access_token)
await tibber_connection.update_info()

home = tibber_connection.get_homes()[0]
await home.update_info()

await home.update_price_info()
tibberPrice = home.current_price_info

# covert dict to json and send to AWSIoTCore
tibberPrice['address'] = TIBBERADDRESS
tibberPrice['timestamp'] = strftime("%Y-%m-%d %H:%M:%S", gmtime())
messageJson = json.dumps(tibberPrice, indent = 4)

#Send to AWSIoT
myawsclient.publish(topic, messageJson)
print('Published topic %s: %s\n' % (topic, messageJson))

await tibber_connection.close_connection()__

if name == 'main':
loop = asyncio.get_event_loop()
while True:
loop.run_until_complete(main())
time.sleep(60)

The following error occurs:
Published topic tibber/price: {
"energy": 3.8703,
"tax": 0.9775,
"total": 4.8478,
"startsAt": "2022-09-05T11:00:00.000+02:00",
"level": "NORMAL",
"address": "XX",
"timestamp": "2022-09-05 09:57:54"
}

hosts = await asyncio.shield(host_resolved)

File "/usr/local/lib/python3.9/site-packages/aiohttp/connector.py", line 880, in _resolve_host

addrs = await self._resolver.resolve(host, port, family=self._family)

File "/usr/local/lib/python3.9/site-packages/aiohttp/resolver.py", line 33, in resolve

infos = await self._loop.getaddrinfo(

File "/usr/local/lib/python3.9/asyncio/base_events.py", line 861, in getaddrinfo

return await self.run_in_executor(

File "/usr/local/lib/python3.9/concurrent/futures/thread.py", line 58, in run

result = self.fn(*self.args, **self.kwargs)

File "/usr/local/lib/python3.9/socket.py", line 954, in getaddrinfo

for res in _socket.getaddrinfo(host, port, family, type, proto, flags):

socket.gaierror: [Errno -2] Name or service not known

The above exception was the direct cause of the following exception:

Traceback (most recent call last):

File "/usr/src/app/./PubSub_Tibber_Price.py", line 80, in

loop.run_until_complete(main())

File "/usr/local/lib/python3.9/asyncio/base_events.py", line 647, in run_until_complete

return future.result()

File "/usr/src/app/./PubSub_Tibber_Price.py", line 49, in main

await tibber_connection.update_info()

File "/usr/local/lib/python3.9/site-packages/tibber/init.py", line 132, in update_info

if (res := await self._execute(query)) is None:

File "/usr/local/lib/python3.9/site-packages/tibber/init.py", line 105, in _execute

return await self._execute(document, variable_values, retry - 1)

File "/usr/local/lib/python3.9/site-packages/tibber/init.py", line 105, in _execute

return await self._execute(document, variable_values, retry - 1)

File "/usr/local/lib/python3.9/site-packages/tibber/init.py", line 98, in _execute

resp = await self.websession.post(API_ENDPOINT, **post_args)

File "/usr/local/lib/python3.9/site-packages/aiohttp/client.py", line 535, in _request

conn = await self._connector.connect(

File "/usr/local/lib/python3.9/site-packages/aiohttp/connector.py", line 542, in connect

proto = await self._create_connection(req, traces, timeout)

File "/usr/local/lib/python3.9/site-packages/aiohttp/connector.py", line 907, in _create_connection

_, proto = await self._create_direct_connection(req, traces, timeout)

File "/usr/local/lib/python3.9/site-packages/aiohttp/connector.py", line 1166, in _create_direct_connection

raise ClientConnectorError(req.connection_key, exc) from exc

aiohttp.client_exceptions.ClientConnectorError: Cannot connect to host api.tibber.com:443 ssl:default [Name or service not known]

Unclosed client session

client_session: <aiohttp.client.ClientSession object at 0xffff9a7bc340>

Unclosed client session

client_session: <aiohttp.client.ClientSession object at 0xffff9a733070>

Unclosed client session

client_session: <aiohttp.client.ClientSession object at 0xffff9a733d00>

Unclosed client session

client_session: <aiohttp.client.ClientSession object at 0xffff98657910>appening:

Any tips about why this is happening?
The error appears everytime I run the code.

pyTibber 0.24.0 does not work with Python 3.10.4

I get the following messages when attempting to run the first sample in the README:

C:\workpriv\balena-homeassistant\peakprice-control\control.py:23: DeprecationWarning: There is no current event loop
  loop = asyncio.get_event_loop()
Arya Stark
Traceback (most recent call last):
  File "C:\workpriv\balena-homeassistant\peakprice-control\control.py", line 24, in <module>
    loop.run_until_complete(main())
  File "C:\Users\rv76\Miniconda3\envs\peakprice-control\lib\asyncio\base_events.py", line 646, in run_until_complete
    return future.result()
  File "C:\workpriv\balena-homeassistant\peakprice-control\control.py", line 12, in main
    home = tibber_connection.get_homes()[0]
IndexError: list index out of range
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x000002C7FD176D40>
Unclosed connector
connections: ['[(<aiohttp.client_proto.ResponseHandler object at 0x000002C7FD15A920>, 121785.375)]']
connector: <aiohttp.connector.TCPConnector object at 0x000002C7FD176DD0>

It works when I downgrade to Python 3.9.13.

Realtime power

Hi... I am trying to read out single (or few) realtime samples of instantaneous power from python. I am uncertain about how to use the (now) pure async examples in a three stage process where I

  1. read a few power samples, with time
  2. Turn on a relay
  3. read a few power sampls again.

This appears a bit tricky to do with the demonstrated asyncio streaming examples..
Is there a way to do single shot http request for example?

Prohibited connection! - Connection error

Hi There.

I'm quite new to python and therefore I don't understand what's going on.

I've used the subscription example from your package and replaced "tibber.const.DEMO_TOKEN" with my token from the tibber developer-website. I also added an "asyncio.run(run())" at the end of the code to run the method. Here is the result:

Prohibited connection! Connection error Traceback (most recent call last): File "/home/pi/.local/lib/python3.7/site-packages/graphql_subscription_manager/__init__.py", line 104, in running msg = await asyncio.wait_for(self.websocket.recv(), timeout=30) File "/usr/lib/python3.7/asyncio/tasks.py", line 416, in wait_for return fut.result() File "/home/pi/.local/lib/python3.7/site-packages/websockets/legacy/protocol.py", line 568, in recv await self.ensure_open() File "/home/pi/.local/lib/python3.7/site-packages/websockets/legacy/protocol.py", line 953, in ensure_open raise self.connection_closed_exc() websockets.exceptions.ConnectionClosedError: received 1011 (unexpected error); then sent 1011 (unexpected error)

Can you help me to get thing running?

Regards
Mark

current power sensor is unavailable

ive had this issue before and it was simply a reboot of the whole pi to get it back up but ive tried rebooting over and over for a few days and nothing is getting this sensor back on.
HA is fully upto date with nothing pending
logs dont say anything either, i have it set for debug
2020-08-10 16:18:04 DEBUG (MainThread) [homeassistant.components.tibber.sensor] Asking for new data
thats the only thing is says for debug.

Not able to run the rt_subscribe

Hi,
First thanks for sharing this code.
I am not sure if it is an issue or something I am doing wrong here.
I am trying to use pyTibber to get the power consumption data in realtime.
However when I run the code "Example realtime data", the output is:

_(py39) ➜ tibber python tibber_pulse.py
<tibber.Tibber object at 0x7fcdaa462490>
home is: <tibber.TibberHome object at 0x7fcdaa3e22e0>
Unexpected error
Traceback (most recent call last):
File "/Users/castrma/miniconda3/envs/py39/lib/python3.9/site-packages/graphql_subscription_manager/init.py", line 143, in running
await self._process_msg(msg)
File "/Users/castrma/miniconda3/envs/py39/lib/python3.9/site-packages/graphql_subscription_manager/init.py", line 302, in _process_msg
await callback(data)
File "/Users/castrma/miniconda3/envs/py39/lib/python3.9/site-packages/tibber/init.py", line 697, in callback_add_extra_data
time = parse(data["data"]["liveMeasurement"]["timestamp"]).astimezone(
KeyError: 'data'

By the way I was able to run the other example and get info on Monthly consumption and cost.

Packages:
graphql-subscription-manager 0.4.3
asyncio 3.4.3
aiohttp 3.8.1
Python 3.9.7

"Timed out when connecting to Tibber"

Integration is working, and im not bothered by this, but it seems to throw Timed out when connecting to Tibber on a regular basis in my installation.

Just to give you an impression, 15-20 each day:
image

Im running Home assistant docker, and its been throwing these for the last few months. Let me know if you want some more details.

websockets.exceptions.ConnectionClosedError: received 4500 (private use)

I constantly getting this ErrorCode:
websockets.exceptions.ConnectionClosedError: received 4500 (private use) Internal server error; then sent 4500 (private use) Internal server error

I´ve checked the Token several times, and in the API-Explorer erverything works fine:-)
Tibber Support can´t help..
THX BastiR

Dependency issue?

In Ubuntu 21.10:

Processing dependencies for pyTibber==0.22.3
error: async-timeout 4.0.2 is installed but async_timeout<4.0,>=3.0 is required by {'aiohttp'}

Feature request: Energy consumption for Tibber customers using emeters

Hi,

would it be possible to include the energy consumption for customers of Tibber that do not use Pulse but have Discovergy meters installed?
I can see my consumption in the Tibber app, and with the new energy feature of HA, it would be very useful to see it directly in the intergration.

Example in README.md is supposed to work?

I pip-installed pyTibber in Python3.9 and tried to run the Example given in the README.md. I got the error message:

Error connecting to Tibber: Cannot connect to host api.tibber.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1123)')]

I also tried with my personal Tibber API key, with the same result.

Is that normal?

Callback not called when using pytibber as docker container

Hi,
First thanks for this repo.
I am running your "real time data" example as a docker container, but the callback does not get called therefore no data.
The container is able to open the session and get_homes.

I have another container that only get the "current_price_info" and this container works well in the same setup.
I assume my issue is around the rt_subscribe using aiohttp websession for the setup that I have.
Have you had such issue before?

Setup:
python3.9.12
docker 20.10.21
docker host: Ubuntu 18.04.6 LTS

requirements.txt:
aiohttp==3.8.1
aiosignal==1.2.0
async-timeout==4.0.2
attrs==22.1.0
charset-normalizer==2.1.0
frozenlist==1.3.0
graphql-subscription-manager
idna==3.3
multidict==6.0.2
numpy==1.23.1
pandas==1.4.3
python-dateutil==2.8.2
pyTibber==0.25.6
boto3 >= 1.20.13
argparse
AWSIoTPythonSDK==1.5.2

I am able to run the realtime python script on the host machine without problem.

Any help recommendation?

home.current_price_data() fails with KeyError

Using the demo api key works fine, but price data is not working.

>>>loop.run_until_complete(home.update_price_info())
>>> home.current_price_info
{'energy': 0.1201, 'tax': 0.1259, 'total': 0.246, 'startsAt': '2022-10-11T15:00:00.000+02:00', 'level': 'NORMAL'}
>>>loop.run_until_complete(home.update_price_info())
>>>home.current_price_data()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/user/Documents/testing/venv/lib/python3.9/site-packages/tibber/tibber_home.py", line 368, in current_price_data
    return round(self.price_total[key], 3), self.price_level[key], price_time
KeyError: '2022-10-11T11:00:00.000+00:00'

as digging around to see how to fix the 2h timezone problem in the homeassistant integration.home-assistant/core#79701

Looking for MicroPhyton or Arduino library for Tibber API

Is there anyone out there who has managed to request Subsctiption real time data, for ESP32 or similar small hardware?.

After the changes in websocket subscriptions...
I'm completely stuck. Even ChatGPT can't handle it.
Now it's up to you Daniel to save the world :)
/Greetings from Sweden

Both README examples are not functinal

yornik@raspberrypi:~ $ python test2.py
  File "/home/yornik/test2.py", line 6
    await tibber_connection.update_info()
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: 'await' outside function
yornik@raspberrypi:~ $ cat test2.py
import tibber.const
import tibber

access_token = tibber.const.DEMO_TOKEN
tibber_connection = tibber.Tibber(access_token, user_agent="change_this")
await tibber_connection.update_info()
print(tibber_connection.name)

home = tibber_connection.get_homes()[0]
await home.update_info()
print(home.address1)

await home.update_price_info()
print(home.current_price_info)

await tibber_connection.close_connection()
yornik@raspberrypi:~ $ cat test.py
import tibber.const
import asyncio

import aiohttp
import tibber

ACCESS_TOKEN = tibber.const.DEMO_TOKEN


def _callback(pkg):
    data = pkg.get("data")
    if data is None:
        return
    print(data.get("liveMeasurement"))


async def run():
    async with aiohttp.ClientSession() as session:
        tibber_connection = tibber.Tibber(ACCESS_TOKEN, websession=session, user_agent="change_this")
        await tibber_connection.update_info()
    home = tibber_connection.get_homes()[0]
    await home.rt_subscribe(_callback)
yornik@raspberrypi:~ $ python test.py
yornik@raspberrypi:~ $

Both examples will do non excepted things.

over time connection problems does not recover properly

Hi Daniel,

I wrote the code below in order to have an async task which should deliver realtime power usage and price_info. Symptom is that over a certain time the tibber connection seems to be "not ok, lost?" and one of the await's never returns rendering the while loop stuxk giving it no chance to disconnect and to beuild up a new connection.

What am i doing wrong? Is there a suggestion to do it better? Note that I checked the queue was read on the other end, such that it cannot be full.

The following observations I found after some further investigation:

  • tibber_connection.rt_disconnect(): this method does not stop the subscription, still activity is reported in the log.

Best regards
Carl.

async def tibberTask():
    #get actual info from tibber and insert this data each second in the command queue
    access_token = "removed as of privacy"
    while True:
        try:
            g_logger.debug("Start tibber login")
            tibber_connection = tibber.Tibber(access_token, user_agent="evcharger")
            await tibber_connection.update_info()
            home = tibber_connection.get_homes(only_active=False)[0]
            await home.update_info()   
            g_logger.debug(f"Tibber account:{tibber_connection.name}")
            g_logger.debug(f"Tibber address:{home.address1}")
            await home.rt_subscribe(_callback)
            while True:
                await home.update_price_info()
                await G_commandQueue.put((Command.ACTUAL_PRICE.value, home.current_price_info['total']))
                await asyncio.sleep(60)    
        except:
            try:
                await tibber_connection.rt_disconnect()
                await tibber_connection.close_connection()
            except:
                pass
            s = traceback.format_exc()
            g_logger.debug(f"handled exception: {s}, waiting for 60 seconds, then retry")
            await asyncio.sleep(60)

Subscription does not work (callback not called)

Hi,
I'm trying to use the realtime data example out of the Readme.me. But the Callback function is never called, even when adding a sleep at the end.
However, when using the API explorer from Tibber, I get data.
I noted at Tibbers documentation the "Breaking change in websocket subscriptions December 2022" description and here in pyTibber the old wss URL is still used. But it is not yet Dec 22, so should be not yet the problem I hope.

Does anyone else have this code currently working ?

EDIT: Changing the URL in SUB_ENDPOINT at

SUB_ENDPOINT = "wss://api.tibber.com/v1-beta/gql/subscriptions"
seems to fix the issue.
and adding a "await asyncio.sleep(120) would also not hurt at the end of the example, since at least with my connection here the default timeout of 10 seconds seems to be a bit on the edge.

Live Measurement

Hello.

Not sure if its a issue or what but i'm trying to use rt_subscribe to get out live measurement, but i'm not sure what to put in the required fields loop and async_callback. Could you please help me?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.