Ejemplo n.º 1
0
async def async_setup(hass, config):
    """Set up the Tibber component."""
    conf = config.get(DOMAIN)

    import tibber

    tibber_connection = tibber.Tibber(
        conf[CONF_ACCESS_TOKEN],
        websession=async_get_clientsession(hass),
        time_zone=dt_util.DEFAULT_TIME_ZONE,
    )
    hass.data[DOMAIN] = tibber_connection

    async def _close(event):
        await tibber_connection.rt_disconnect()

    hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, _close)

    try:
        await tibber_connection.update_info()
    except asyncio.TimeoutError as err:
        _LOGGER.error("Timeout connecting to Tibber: %s ", err)
        return False
    except aiohttp.ClientError as err:
        _LOGGER.error("Error connecting to Tibber: %s ", err)
        return False
    except tibber.InvalidLogin as exp:
        _LOGGER.error("Failed to login. %s", exp)
        return False

    for component in ["sensor", "notify"]:
        discovery.load_platform(hass, component, DOMAIN, {CONF_NAME: DOMAIN},
                                config)

    return True
Ejemplo n.º 2
0
async def async_setup_entry(hass, entry):
    """Set up a config entry."""

    tibber_connection = tibber.Tibber(
        access_token=entry.data[CONF_ACCESS_TOKEN],
        websession=async_get_clientsession(hass),
        time_zone=dt_util.DEFAULT_TIME_ZONE,
    )
    hass.data[DOMAIN] = tibber_connection

    async def _close(event):
        await tibber_connection.rt_disconnect()

    entry.async_on_unload(
        hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, _close))

    try:
        await tibber_connection.update_info()
    except asyncio.TimeoutError as err:
        raise ConfigEntryNotReady from err
    except aiohttp.ClientError as err:
        _LOGGER.error("Error connecting to Tibber: %s ", err)
        return False
    except tibber.InvalidLogin as exp:
        _LOGGER.error("Failed to login. %s", exp)
        return False

    hass.config_entries.async_setup_platforms(entry, PLATFORMS)

    # set up notify platform, no entry support for notify component yet,
    # have to use discovery to load platform.
    hass.async_create_task(
        discovery.async_load_platform(hass, "notify", DOMAIN, {},
                                      hass.data[DATA_HASS_CONFIG]))
    return True
Ejemplo n.º 3
0
    async def load_data(now=None):
        nonlocal last_update, tibber_home, prices, dates
        if dt_util.now() - last_update < datetime.timedelta(hours=10):
            return

        if tibber_home is None:
            tibber_connection = tibber.Tibber(
                config[DOMAIN].get(CONF_ACCESS_TOKEN),
                websession=async_get_clientsession(hass))
            await tibber_connection.update_info()
            for tibber_home in tibber_connection.get_homes():
                await tibber_home.update_info()
                if 'hamretunet' in tibber_home.info['viewer']['home'][
                        'appNickname'].lower():
                    break

        await tibber_home.update_price_info()
        prices = []
        dates = []
        for key, price_total in tibber_home.price_total.items():
            prices.append(price_total * 100)
            dates.append(dt_util.as_local(dt_util.parse_datetime(key)))

        if len(dates) > 24 or dt_util.now().hour < 12:
            last_update = dt_util.now()
            await heating()
Ejemplo n.º 4
0
 def setUp(self):  # pylint: disable=invalid-name
     """ things to be run when tests are started. """
     async def _create_session():
         return aiohttp.ClientSession()
     loop = asyncio.get_event_loop()
     self.websession = loop.run_until_complete(_create_session())
     self.tibber = tibber.Tibber(websession=self.websession)
     self.tibber.sync_update_info()
Ejemplo n.º 5
0
async def test_tibber_invalid_token():
    async with aiohttp.ClientSession() as session:
        tibber_connection = tibber.Tibber(access_token="INVALID_TOKEN",
                                          websession=session)
        with pytest.raises(tibber.InvalidLogin,
                           match="No valid access token in request"):
            await tibber_connection.update_info()
        assert tibber_connection.name is None
        assert tibber_connection.get_homes() == []
Ejemplo n.º 6
0
async def test_tibber_token():
    async with aiohttp.ClientSession() as session:
        tibber_connection = tibber.Tibber(
            access_token=
            "d11a43897efa4cf478afd659d6c8b7117da9e33b38232fd454b0e9f28af98012",
            websession=session,
        )
        await tibber_connection.update_info()

        assert tibber_connection.name == "Daniel Høyer"
        assert len(tibber_connection.get_homes()) == 0
        assert len(tibber_connection.get_homes(only_active=False)) == 0
Ejemplo n.º 7
0
async def test_tibber():
    async with aiohttp.ClientSession() as session:
        tibber_connection = tibber.Tibber(websession=session)
        await tibber_connection.update_info()

        assert tibber_connection.name == "Arya Stark"
        assert len(tibber_connection.get_homes()) == 1

        assert tibber_connection.get_home("INVALID_KEY") is None

        k = 0
        for home in tibber_connection.get_homes(only_active=False):
            await home.update_info()
            if home.home_id == "c70dcbe5-4485-4821-933d-a8a86452737b":
                k += 1
                assert home.home_id == "c70dcbe5-4485-4821-933d-a8a86452737b"
                assert home.address1 == "Kungsgatan 8"
                assert home.country == "SE"
                assert home.price_unit == "SEK/kWh"
                assert home.has_real_time_consumption

                assert home.current_price_total is None
                assert home.price_total == {}
                assert home.current_price_info == {}

                home.sync_update_current_price_info()
                assert home.current_price_total > 0
                assert isinstance(home.current_price_info.get("energy"),
                                  (float, int))
                assert isinstance(home.current_price_info.get("startsAt"), str)
                assert isinstance(home.current_price_info.get("tax"),
                                  (float, int))
                assert isinstance(home.current_price_info.get("total"),
                                  (float, int))

                await home.update_price_info()
                for key in home.price_total.keys():
                    assert isinstance(key, str)
                    assert isinstance(home.price_total[key], (float, int))
            else:
                k += 1
                assert home.home_id == "cc83e83e-8cbf-4595-9bf7-c3cf192f7d9c"
                assert home.address1 == "Winterfell Castle 1"
                assert home.country is None
                assert home.price_unit == "NOK/kWh"
                assert home.has_real_time_consumption

        assert k == 1

        assert len(tibber_connection.get_homes()) == 1
        await tibber_connection.update_info()
        assert len(tibber_connection.get_homes()) == 1
Ejemplo n.º 8
0
async def async_setup_platform(hass, config, add_devices, discovery_info=None):
    """Setup component."""
    import tibber
    tibber_connection = tibber.Tibber(config.get(CONF_ACCESS_TOKEN),
                                      websession=async_get_clientsession(hass))
    try:
        await tibber_connection.update_info()
        dev = []
        for tibber_home in tibber_connection.get_homes():
            await tibber_home.update_info()
            if 'hamretunet' in tibber_home.info['viewer']['home'][
                    'appNickname'].lower():
                break
    except (asyncio.TimeoutError, aiohttp.ClientError):
        raise PlatformNotReady()
    add_devices([vv(tibber_home, hass)])
Ejemplo n.º 9
0
async def async_setup_platform(hass, config, async_add_entities,
                               discovery_info=None):
    """Set up the Tibber sensor."""
    import tibber
    tibber_connection = tibber.Tibber(config[CONF_ACCESS_TOKEN],
                                      websession=async_get_clientsession(hass))

    try:
        await tibber_connection.update_info()
        dev = []
        for home in tibber_connection.get_homes():
            await home.update_info()
            dev.append(TibberSensor(home))
    except (asyncio.TimeoutError, aiohttp.ClientError):
        raise PlatformNotReady()

    async_add_entities(dev, True)
Ejemplo n.º 10
0
    async def async_step_user(self, user_input=None):
        """Handle the initial step."""

        if self._async_current_entries():
            return self.async_abort(reason="already_configured")

        if user_input is not None:
            access_token = user_input[CONF_ACCESS_TOKEN].replace(" ", "")

            tibber_connection = tibber.Tibber(
                access_token=access_token,
                websession=async_get_clientsession(self.hass),
            )

            errors = {}

            try:
                await tibber_connection.update_info()
            except asyncio.TimeoutError:
                errors[CONF_ACCESS_TOKEN] = "timeout"
            except aiohttp.ClientError:
                errors[CONF_ACCESS_TOKEN] = "cannot_connect"
            except tibber.InvalidLogin:
                errors[CONF_ACCESS_TOKEN] = "invalid_access_token"

            if errors:
                return self.async_show_form(
                    step_id="user",
                    data_schema=DATA_SCHEMA,
                    errors=errors,
                )

            unique_id = tibber_connection.user_id
            await self.async_set_unique_id(unique_id)
            self._abort_if_unique_id_configured()

            return self.async_create_entry(
                title=tibber_connection.name,
                data={CONF_ACCESS_TOKEN: access_token},
            )

        return self.async_show_form(
            step_id="user",
            data_schema=DATA_SCHEMA,
            errors={},
        )
Ejemplo n.º 11
0
async def async_setup(hass, config, retry_delay=FIRST_RETRY_TIME):
    """Set up the Tibber component."""
    conf = config.get(DOMAIN)

    tibber_connection = tibber.Tibber(
        conf[CONF_ACCESS_TOKEN],
        websession=async_get_clientsession(hass),
        time_zone=dt_util.DEFAULT_TIME_ZONE,
    )
    hass.data[DOMAIN] = tibber_connection

    async def _close(event):
        await tibber_connection.rt_disconnect()

    hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, _close)

    try:
        await tibber_connection.update_info()
    except asyncio.TimeoutError:
        _LOGGER.warning("Timeout connecting to Tibber. Will retry in %ss",
                        retry_delay)

        async def retry_setup(now):
            """Retry setup if a timeout happens on Tibber API."""
            await async_setup(hass,
                              config,
                              retry_delay=min(2 * retry_delay, 900))

        async_call_later(hass, retry_delay, retry_setup)

        return True
    except aiohttp.ClientError as err:
        _LOGGER.error("Error connecting to Tibber: %s ", err)
        return False
    except tibber.InvalidLogin as exp:
        _LOGGER.error("Failed to login. %s", exp)
        return False

    for component in ["sensor", "notify"]:
        discovery.load_platform(hass, component, DOMAIN, {CONF_NAME: DOMAIN},
                                config)

    return True
Ejemplo n.º 12
0
    async def load_data(now=None):
        nonlocal tibber_home, prices, dates

        def skip():
            if not dates:
                return False
            for _date in dates:
                if (dt_util.now() -
                        datetime.timedelta(days=1)).date == _date.date:
                    return False
            for _date in dates:
                if (dt_util.now() + datetime.timedelta(days=1)
                    ).date == _date.date and dt_util.now().hour >= 12:
                    return True
            return False

        if skip():
            return

        if tibber_home is None:
            tibber_connection = tibber.Tibber(
                config[DOMAIN].get(CONF_ACCESS_TOKEN),
                websession=async_get_clientsession(hass))
            await tibber_connection.update_info()
            for tibber_home in tibber_connection.get_homes():
                await tibber_home.update_info()
                if 'hamretunet' in tibber_home.info['viewer']['home'][
                        'appNickname'].lower():
                    break

        await tibber_home.update_price_info()
        prices = []
        dates = []
        for key, price_total in tibber_home.price_total.items():
            prices.append(price_total * 100)
            dates.append(dt_util.as_local(dt_util.parse_datetime(key)))

        if len(dates) > 24 or dt_util.utcnow().hour < 12:
            await generate_fig_call()
Ejemplo n.º 13
0
async def async_setup(hass, config):
    """Set up the Tibber component."""
    conf = config.get(DOMAIN)

    import tibber
    tibber_connection = tibber.Tibber(conf[CONF_ACCESS_TOKEN],
                                      websession=async_get_clientsession(hass))
    hass.data[DOMAIN] = tibber_connection

    async def _close(event):
        await tibber_connection.rt_disconnect()

    hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, _close)

    try:
        await tibber_connection.update_info()
    except (asyncio.TimeoutError, aiohttp.ClientError):
        return False

    for component in ['sensor', 'notify']:
        discovery.load_platform(hass, component, DOMAIN,
                                {CONF_NAME: DOMAIN}, config)

    return True
Ejemplo n.º 14
0
tibberhomes_only_active = str(os.getenv('TIBBER_HOMES_ONLYACTIVE', 'True'))
loadHistory = os.getenv('LOAD_HISTORY', 'FALSE')
debug = os.getenv('DEBUG', 'False')

if str2bool(debug):
    print("Influxdb Host: " + influxuser + "@" + influxhost + ":" +
          str(influxport))
    print("Influxdb Password: "******"Influxdb DB: " + influxdb)
    print("Tibber Token: " + tibbertoken)
    print("Only Active Homes: " + tibberhomes_only_active)
    print("Load History: " + loadHistory)

client = InfluxDBClient(influxhost, influxport, influxuser, influxpw, influxdb)

tibber_connection = tibber.Tibber(tibbertoken)
tibber_connection.sync_update_info()
#print(tibber_connection.name)

if str2bool(tibberhomes_only_active):
    homes = tibber_connection.get_homes(only_active=True)
else:
    homes = tibber_connection.get_homes(only_active=False)

for home in homes:
    home.sync_update_info()
    address = home.address1
    if str2bool(debug):
        print("Home Address: " + address)
    #print(home.address1)
    home.sync_update_price_info()
Ejemplo n.º 15
0
async def test_tibber_notification():
    async with aiohttp.ClientSession() as session:
        tibber_connection = tibber.Tibber(websession=session)
        await tibber_connection.update_info()
        assert not await tibber_connection.send_notification(
            "Test tittle", "message")
Ejemplo n.º 16
0
 def setUp(self):     # pylint: disable=invalid-name
     """ things to be run when tests are started. """
     self.tibber = tibber.Tibber(access_token='INVALID_TOKEN')        
     self.assertRaises(tibber.InvalidLogin, self.tibber.sync_update_info)
Ejemplo n.º 17
0
 def setUp(self):     # pylint: disable=invalid-name
     """ things to be run when tests are started. """
     self.tibber = tibber.Tibber(access_token='d11a43897efa4cf478afd659d6c8b7117da9e33b38232fd454b0e9f28af98012')
     self.tibber.sync_update_info()
Ejemplo n.º 18
0
async def test_tibber_no_session():
    tibber_connection = tibber.Tibber()
    await tibber_connection.update_info()

    assert tibber_connection.name == "Arya Stark"
Ejemplo n.º 19
0
 def setUp(self):     # pylint: disable=invalid-name
     """ things to be run when tests are started. """
     self.tibber = tibber.Tibber()
     self.tibber.sync_update_info()
Ejemplo n.º 20
0
import datetime
import tibber
import json
import settings
tibber_connection = tibber.Tibber(settings.access_token)
tibber_connection.sync_update_info()
#print(tibber_connection.name)
home = tibber_connection.get_homes()[0]
#home.sync_update_info()
#print(home.address1)

home.sync_update_price_info()
print(home.current_price_info)
print(home.price_total)
#print(home.current_price_total)
#test = []
count = 0
prices = json.loads(str(home.price_total).replace("'", '"'))
tibber_connection.sync_close_connection()
#Generate variables for dates
date_today = datetime.date.today()
one_day = datetime.timedelta(days=1)
date_tomorrow = date_today + one_day

today_series = ""
tomorrow_series = ""
while count < 24:
    s = "0" + str(count)
    hour = s[-2:]
    datetime_today = str(date_today)+"T"+hour+':00:00+02:00'
    datetime_tomorrow = str(date_tomorrow) + "T" + hour + ':00:00+02:00'