py-smart-gardena / hass-gardena-smart-system

Home Assistant custom component integration for Gardena Smart System
Apache License 2.0
208 stars 52 forks source link

Error re-connecting after 24h #136

Open jaydkay opened 2 years ago

jaydkay commented 2 years ago

Since yesterday I'm running HA 2022.7.6 along with HACS 1.26.2 and the Gardena integration 1.0.0-0b906.

This has been working fine for about 24h, with the Gardena integration disconnecting about every 2h and always reconnecting about 10-20s later (I think I read somewhere that this is normal behaviour).

Unfortunately, after 24h, it is disconnecting again and stays disconnected with the following error in the logs:

Logger: homeassistant Source: /usr/src/homeassistant/homeassistant/runner.py:96 First occurred: 09:09:17 (1 occurrences) Last logged: 09:09:17 Error doing job: Task exception was never retrieved

Traceback (most recent call last): File "/usr/local/lib/python3.10/site-packages/gardena/smart_system.py", line 185, in start_ws ws_url = await self.get_ws_url(location) File "/usr/local/lib/python3.10/site-packages/backoff/_async.py", line 133, in retry ret = await target(*args, **kwargs) File "/usr/local/lib/python3.10/site-packages/gardena/smart_system.py", line 209, in get_ws_url r = await self.client.post( File "/usr/local/lib/python3.10/site-packages/httpx/_client.py", line 1842, in post return await self.request( File "/usr/local/lib/python3.10/site-packages/authlib/integrations/httpx_client/oauth2_client.py", line 88, in request await self.ensure_active_token() File "/usr/local/lib/python3.10/site-packages/authlib/integrations/httpx_client/oauth2_client.py", line 105, in ensure_active_token token = await self.fetch_token(url, grant_type='client_credentials') File "/usr/local/lib/python3.10/site-packages/authlib/integrations/httpx_client/oauth2_client.py", line 118, in _fetch_token resp = await self.post( File "/usr/local/lib/python3.10/site-packages/httpx/_client.py", line 1842, in post return await self.request( File "/usr/local/lib/python3.10/site-packages/authlib/integrations/httpx_client/oauth2_client.py", line 92, in request return await super(AsyncOAuth2Client, self).request( File "/usr/local/lib/python3.10/site-packages/httpx/_client.py", line 1514, in request request = self.build_request( File "/usr/local/lib/python3.10/site-packages/httpx/_client.py", line 344, in build_request url = self._merge_url(url) File "/usr/local/lib/python3.10/site-packages/httpx/_client.py", line 374, in _merge_url merge_url = URL(url) File "/usr/local/lib/python3.10/site-packages/httpx/_urls.py", line 102, in init raise TypeError( TypeError: Invalid type for url. Expected str or httpx.URL, got <class 'NoneType'>: None

I think I have tried all the suggestions in the various issues that are currently investigated, including registering a new new application on the Husqvarna Dev page and re-connecting the APIs.

Did I still miss something and this is a known issue? Any ideas on how to resolve this?

Best regards, Jochen

Coxeroni commented 2 years ago

Same here, same error after approx. 24h with 1.0.0-0b906

te-hb-whatever commented 2 years ago

That's because url is still missing from the metadata - see my comment.

The authlib httpx integration OAuth2Client needs the token_endpoint url. Otherwise it cannot refresh the token in the ensure_active_token method. See:

async def ensure_active_token(self, token):
        async with self._token_refresh_lock:
            if self.token.is_expired():
                refresh_token = token.get('refresh_token')
                url = self.metadata.get('token_endpoint')
                if refresh_token and url:
                    await self.refresh_token(url, refresh_token=refresh_token)
                elif self.metadata.get('grant_type') == 'client_credentials':
                    access_token = token['access_token']
                    new_token = await self.fetch_token(url, grant_type='client_credentials')
                    if self.update_token:
                        await self.update_token(new_token, access_token=access_token)
                else:
                    raise InvalidTokenError()

There ist your error - we need url = self.metadata.get('token_endpoint') in the fetch_token call. And it comes from the client init call.

Or in our case - it doesn't.

vinnyspb commented 2 years ago

I made a workaround for myself which effectively reloads the whole integration once it gets stuck. To do that, I added a new reload method into __init__.py of the integration:

async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Unload a config entry."""
    _LOGGER.debug("Unloading Gardena Smart System component")
    try:
        await hass.data[DOMAIN][GARDENA_SYSTEM].stop()
    except:
        _LOGGER.error('Failed to stop Gardena integration: %s', ex)
    unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
    if unload_ok:
        hass.data[DOMAIN].pop(GARDENA_SYSTEM)

    return unload_ok

and then created an automation:

  trigger:
    - platform: state
      entity_id: binary_sensor.gardena_smart_system_connection
      to: "off"
      for:
        minutes: 5
  action:
    - service: homeassistant.reload_config_entry
      target:
        entity_id: vacuum.sileno

Hope that helps until the issue is fixed permanently.

crazyfx1 commented 2 years ago

You can test the new version by updating the version the manifest.json in custom_components/gardena_smart_system to 1.3.7 and restart HA.

  "requirements": ["py-smart-gardena==1.3.7"] 

Or wait until a new version of the component is released on HACS.

jaydkay commented 2 years ago

I think there is no need for that: There is already a new Pre-Release 1.0.0-0b907 available. Unfortunately, it doesn't work for me: The integration now takes about 5 minutes to load (so it delays the startup of HA) and then refuses to work. In the logs it mentions 429 : Limit Exceeded and then it waits an increasing amount of time until a maximum of 300s or so.

crazyfx1 commented 2 years ago

Ok I didn't see the Prerelease.

The 429 error is another problem, which was not fixed by this change.

jaydkay commented 2 years ago

Okay, let me check again. I'm only seeing the error 429 since upgrading from 1.0.0-0b906 to 1.0.0-0b907 this morning...

jaydkay commented 2 years ago

Just downgraded from 1.0.0-0b907 to 1.0.0-0b906 and error 429 has disappeared. The integration starts up without errors, no delay in HA startup, etc.

crazyfx1 commented 2 years ago

The 1.0.0-0b907 works perfectly for me for over a week now.

Coxeroni commented 2 years ago

Not for me. b907 also disconnected some time ago.

larsxschneider commented 2 years ago

Just another data point: for me b907 disconnected, too.

@crazyfx1 What "Redirect URL" did you define when you created the Husqvarna Application? (I haven't digged into that error yet... so I don't know if this is a relevant aspect).

crazyfx1 commented 2 years ago

I have it on http://localhost:8080, so I guess it doesn't matter.

larsxschneider commented 2 years ago

FYI: The problem fixed itself for me. My Gardena API connection is now stable with b907.

tomsommer commented 2 years ago

Confirmed, it still disconnects periodically with b907, but it reconnects just after - much better than b906 where it just lost connection.

PaulErdbeck commented 2 years ago

b907 works for me, too, since one week. Disconnect all 2h but reconnecting instantly. Thanks for the effort!

PaulErdbeck commented 2 years ago

...works for 6 days since next disconnection without reconnecting...:-( Is there a possibility to reconnect manually without restart HA?