Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

This is for those users in the EU region continuing to have issues... #2483

Open
danielbrunt57 opened this issue Aug 24, 2024 · 75 comments
Open

Comments

@danielbrunt57
Copy link
Collaborator

Describe the bug

For those users in the EU region continuing to have issues.

System details

  • Home Assistant version: 2024.8.2
  • alexa_media version (from const.py or HA startup log): 4.12.11
  • alexapy version (from pip show alexapy in homeasssistant container or HA startup log): => 1.28.2
  • Is Amazon 2FA/2SV enabled <!---We will not debug login issues if unanswered---> (y/n): Yes
  • Amazon Domains:
    • .be
    • .berlin
    • .ch
    • .co.uk
    • .cz
    • .de
    • .es
    • .eu
    • .fi
    • .fr
    • .gg
    • .im
    • it
    • .me
    • .me.uk
    • .nl
    • .org.uk
    • .ruhr
    • .se
    • .uk
    • .wien

Debug Logs (alexa_media & alexapy)

Result of successful http2 communication:

2024-08-23 22:41:41.599 DEBUG (MainThread) [custom_components.alexa_media] d****l@b******a: HTTP2 created: <alexapy.alexahttp2.HTTP2EchoClient object at 0xffff7ed41ee0>
2024-08-23 22:41:41.599 DEBUG (MainThread) [custom_components.alexa_media] d****l@b******a: HTTP2push successfully connected
2024-08-23 22:41:41.606 DEBUG (MainThread) [alexapy.alexahttp2] Starting message parsing loop.
2024-08-23 22:41:41.606 DEBUG (MainThread) [alexapy.alexahttp2] Connecting to https://alexa.na.gateway.devices.a2z.com/v20160207/directives with {'method': 'GET', 'path': '/v20160207/directives', 'authority': 'alexa.na.gateway.devices.a2z.com', 'scheme': 'https', 'authorization': 'Bearer Atna|<redacted>'}
2024-08-23 22:41:41.607 DEBUG (MainThread) [alexapy.alexahttp2] Preparing ping to https://alexa.na.gateway.devices.a2z.com/ping
2024-08-23 22:41:45.724 DEBUG (MainThread) [alexapy.alexahttp2] Received raw message: --------abcde123
2024-08-23 22:41:45.828 DEBUG (MainThread) [alexapy.alexahttp2] Received response: 204:

What to try

In const.py, try editing these constants as follows:
From:

SCAN_INTERVAL = timedelta(seconds=60)
MIN_TIME_BETWEEN_FORCED_SCANS = timedelta(seconds=1)
DEFAULT_SCAN_INTERVAL = 60

To:

SCAN_INTERVAL = timedelta(seconds=180)
MIN_TIME_BETWEEN_FORCED_SCANS = timedelta(seconds=5)
DEFAULT_SCAN_INTERVAL = 300

I'm most interested in whether MIN_TIME_BETWEEN_FORCED_SCANS has a positive effect or not as the integration only retries 5 times with an increasing backoff in time in between, which may not be enough to prevent Amazon EU from shutting down.

It's a shot in the dark since I'm in the NA region (amazon.ca) and do not have your issues...

@danielbrunt57
Copy link
Collaborator Author

If it works out that a change in one or more of these works out for EU, I can see if I can make them configurable from the UI...

@LMantovan
Copy link

@danielbrunt57 It seems working here from Italy. I changed all the configuration you suggest

@voyagerft
Copy link

in Italy it doesn't work, the reconfiguration pop up appears continuously

IMG_3799

@figorr
Copy link

figorr commented Aug 24, 2024

Updated AMP to 4.2.11 under Supervisor 2024.7.4 and then I updated to 2024.8.2.

Domain .es

Edited files:

File 1: manifest.json
"requirements": ["alexapy>=1.28.2", "packaging>=20.3", "wrapt>=1.14.0"],

File 2: const.py
SCAN_INTERVAL = timedelta(seconds=180)
MIN_TIME_BETWEEN_FORCED_SCANS = timedelta(seconds=5)
DEFAULT_SCAN_INTERVAL = 300

I didn't see error at logs after restarting HA. But after 10 minutes I could see the following warnings.

Warning 1:

Registrador: homeassistant
Fuente: /usr/src/homeassistant/homeassistant/runner.py:148
Ocurrió por primera vez: 19:22:46 (1 ocurrencias)
Último inicio de sesión: 19:22:46

Error doing job: Task exception was never retrieved (None)
Traceback (most recent call last):
  File "/usr/local/lib/python3.12/site-packages/alexapy/helpers.py", line 137, in wrapper
    return await func(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/alexapy/alexaapi.py", line 889, in send_tts
    await self.send_sequence(
  File "/usr/local/lib/python3.12/site-packages/alexapy/helpers.py", line 137, in wrapper
    return await func(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/alexapy/alexaapi.py", line 512, in send_sequence
    await self.run_behavior(node_data, queue_delay=queue_delay)
  File "/usr/local/lib/python3.12/site-packages/alexapy/helpers.py", line 137, in wrapper
    return await func(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/alexapy/alexaapi.py", line 434, in run_behavior
    await self._post_request("/api/behaviors/preview", data=data)
  File "/usr/local/lib/python3.12/site-packages/alexapy/alexaapi.py", line 226, in _post_request
    return await self._request("post", uri, data, query)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/backoff/_async.py", line 151, in retry
    ret = await target(*args, **kwargs)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/alexapy/alexaapi.py", line 199, in _request
    raise AlexapyLoginError("Login error detected; not contacting API")
alexapy.errors.AlexapyLoginError: Login error detected; not contacting API

Warning 2:

Registrador: alexapy.helpers
Fuente: runner.py:190
Ocurrió por primera vez: 19:22:46 (3 ocurrencias)
Último inicio de sesión: 19:22:46

alexaapi.run_behavior((<alexapy.alexaapi.AlexaAPI object at 0x7fbdb9791460>, {'@type': 'com.amazon.alexa.behaviors.model.OpaquePayloadOperationNode', 'type': 'Alexa.Speak', 'operationPayload': {'deviceType': 'A3RBAYBE7VM004', 'deviceSerialNumber': 'G************30N', 'locale': 'es-es', 'customerId': 'A*****************VKG', 'textToSpeak': 'La temperatura de jardín es de 27.1 grados.', 'target': {'customerId': 'A*****************VKG', 'devices': [{'deviceSerialNumber': 'G************30N', 'deviceTypeId': 'A3RBAYBE7VM004'}]}, 'skillId': 'amzn1.ask.1p.saysomething'}}), {'queue_delay': 1.5}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments: ('Login error detected; not contacting API',)
alexaapi.send_sequence((<alexapy.alexaapi.AlexaAPI object at 0x7fbdb9791460>, 'Alexa.Speak'), {'customer_id': 'A*****************VKG', 'textToSpeak': 'La temperatura de jardín es de 27.1 grados.', 'target': {'customerId': 'A*****************VKG', 'devices': [{'deviceSerialNumber': 'G************30N', 'deviceTypeId': 'A3RBAYBE7VM004'}]}, 'skillId': 'amzn1.ask.1p.saysomething', 'queue_delay': 1.5}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments: ('Login error detected; not contacting API',)
alexaapi.send_tts((<alexapy.alexaapi.AlexaAPI object at 0x7fbdb9791460>, 'La temperatura de jardín es de 27.1 grados.'), {'customer_id': 'A*****************VKG', 'queue_delay': 1.5}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments: ('Login error detected; not contacting API',)

Warning 3:

Este error se originó a partir de una integración personalizada.

Registrador: alexapy.helpers
Fuente: custom_components/alexa_media/__init__.py:786
integración: Alexa Media Player (documentación, problemas)
Ocurrió por primera vez: 19:20:43 (6 ocurrencias)
Último inicio de sesión: 19:22:43

alexaapi.get_customer_history_records((<alexapy.alexalogin.AlexaLogin object at 0x7fbdb7a34a70>,), {'max_record_size': 10}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments: ('Unauthorized',)
alexaapi.get_last_device_serial((<alexapy.alexalogin.AlexaLogin object at 0x7fbdb7a34a70>,), {}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments: ('Unauthorized',)
alexaapi.get_customer_history_records((<alexapy.alexalogin.AlexaLogin object at 0x7fbdb7a34a70>,), {'max_record_size': 10}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments: ('Login error detected; not contacting API',)
alexaapi.get_last_device_serial((<alexapy.alexalogin.AlexaLogin object at 0x7fbdb7a34a70>,), {}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments: ('Login error detected; not contacting API',)

Then I reloaded the integration and I got the following errors at log.

Error 1:

Registrador: homeassistant.config_entries
Fuente: config_entries.py:819
Ocurrió por primera vez: 19:35:47 (2 ocurrencias)
Último inicio de sesión: 19:36:27

Error unloading entry Alexa for notify
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/config_entries.py", line 819, in async_unload
    result = await component.async_unload_entry(hass, self)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/components/notify/__init__.py", line 135, in async_unload_entry
    return await component.async_unload_entry(entry)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/helpers/entity_component.py", line 202, in async_unload_entry
    raise ValueError("Config entry was never loaded!")
ValueError: Config entry was never loaded!

Error 2:

Este error se originó a partir de una integración personalizada.

Registrador: alexapy.helpers
Fuente: custom_components/alexa_media/alexa_entity.py:336
integración: Alexa Media Player (documentación, problemas)
Ocurrió por primera vez: 19:36:20 (1 ocurrencias)
Último inicio de sesión: 19:36:20

alexaapi.get_entity_state((<alexapy.alexalogin.AlexaLogin object at 0x7fbdb6136060>,), {'entity_ids': ['*** edited ***']}): Timeout error occurred accessing AlexaAPI: An exception of type CancelledError occurred. Arguments: ()

@elvisgallegos
Copy link

Hi, same error here, also for the ".es" domain

2024-08-24 19:35:47.590 ERROR (MainThread) [homeassistant] Error doing job: Task exception was never retrieved (None)
Traceback (most recent call last):
  File "/usr/local/lib/python3.12/site-packages/alexapy/helpers.py", line 137, in wrapper
    return await func(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/alexapy/alexaapi.py", line 889, in send_tts
    await self.send_sequence(
  File "/usr/local/lib/python3.12/site-packages/alexapy/helpers.py", line 137, in wrapper
    return await func(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/alexapy/alexaapi.py", line 512, in send_sequence
    await self.run_behavior(node_data, queue_delay=queue_delay)
  File "/usr/local/lib/python3.12/site-packages/alexapy/helpers.py", line 137, in wrapper
    return await func(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/alexapy/alexaapi.py", line 434, in run_behavior
    await self._post_request("/api/behaviors/preview", data=data)
  File "/usr/local/lib/python3.12/site-packages/alexapy/alexaapi.py", line 226, in _post_request
    return await self._request("post", uri, data, query)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/backoff/_async.py", line 151, in retry
    ret = await target(*args, **kwargs)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/alexapy/alexaapi.py", line 199, in _request
    raise AlexapyLoginError("Login error detected; not contacting API")
alexapy.errors.AlexapyLoginError: Login error detected; not contacting API
2024-08-24 19:35:53.146 WARNING (MainThread) [alexapy.helpers] alexaapi.run_behavior((<alexapy.alexaapi.AlexaAPI object at 0x7fd007b0dfa0>, {'@type': 'com.amazon.alexa.behaviors.model.OpaquePayloadOperationNode', 'type': 'Alexa.Speak', 'operationPayload': {'deviceType': 'A32DOYMUN6DTXA', 'deviceSerialNumber': 'G************6J9', 'locale': 'es-es', 'customerId': 'A**********W1S', 'textToSpeak': 'Hola', 'target': {'customerId': 'A**********W1S', 'devices': [{'deviceSerialNumber': 'G************6J9', 'deviceTypeId': 'A32DOYMUN6DTXA'}]}, 'skillId': 'amzn1.ask.1p.saysomething'}}), {'queue_delay': 1.5}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments:
('Login error detected; not contacting API',)
2024-08-24 19:35:53.147 WARNING (MainThread) [alexapy.helpers] alexaapi.send_sequence((<alexapy.alexaapi.AlexaAPI object at 0x7fd007b0dfa0>, 'Alexa.Speak'), {'customer_id': 'A3PPHYUAMHCW1S', 'textToSpeak': 'Hola', 'target': {'customerId': 'A**********W1S', 'devices': [{'deviceSerialNumber': 'G************6J9', 'deviceTypeId': 'A32DOYMUN6DTXA'}]}, 'skillId': 'amzn1.ask.1p.saysomething', 'queue_delay': 1.5}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments:
('Login error detected; not contacting API',)
2024-08-24 19:35:53.148 WARNING (MainThread) [alexapy.helpers] alexaapi.send_tts((<alexapy.alexaapi.AlexaAPI object at 0x7fd007b0dfa0>, 'Hola'), {'customer_id': 'A3PPHYUAMHCW1S', 'queue_delay': 1.5}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments:
('Login error detected; not contacting API',)

Also getting this error below in the logs:

2024-08-24 19:36:12.181 ERROR (MainThread) [homeassistant.config_entries] Error unloading entry blah.redacted.blah - amazon.es for notify
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/config_entries.py", line 819, in async_unload
    result = await component.async_unload_entry(hass, self)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/components/notify/__init__.py", line 135, in async_unload_entry
    return await component.async_unload_entry(entry)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/helpers/entity_component.py", line 202, in async_unload_entry
    raise ValueError("Config entry was never loaded!")
ValueError: Config entry was never loaded!
2024-08-24 19:36:12.255 WARNING (MainThread) [custom_components.alexa_media] Could not remove cookiefile: /config/.storage/alexa_media.blah.redacted.blah.pickle.  Please manually delete the file.

I manually deleted the .pickle file, but it is recreated and the error repeats.

@airzl
Copy link

airzl commented Aug 24, 2024

Did not check what was changed, but a reinstall of the previous version saved it immediately.

@danielbrunt57
Copy link
Collaborator Author

Updated AMP to 4.2.11 under Supervisor 2024.7.4 and then I updated to 2024.8.2.

Domain .es

Edited files:

File 1: manifest.json "requirements": ["alexapy>=1.28.2", "packaging>=20.3", "wrapt>=1.14.0"],

File 2: const.py SCAN_INTERVAL = timedelta(seconds=180) MIN_TIME_BETWEEN_FORCED_SCANS = timedelta(seconds=5) DEFAULT_SCAN_INTERVAL = 300

I didn't see error at logs after restarting HA. But after 10 minutes I could see the following warnings.

Warning 1:

Registrador: homeassistant
Fuente: /usr/src/homeassistant/homeassistant/runner.py:148
Ocurrió por primera vez: 19:22:46 (1 ocurrencias)
Último inicio de sesión: 19:22:46

Error doing job: Task exception was never retrieved (None)
Traceback (most recent call last):
  File "/usr/local/lib/python3.12/site-packages/alexapy/helpers.py", line 137, in wrapper
    return await func(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/alexapy/alexaapi.py", line 889, in send_tts
    await self.send_sequence(
  File "/usr/local/lib/python3.12/site-packages/alexapy/helpers.py", line 137, in wrapper
    return await func(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/alexapy/alexaapi.py", line 512, in send_sequence
    await self.run_behavior(node_data, queue_delay=queue_delay)
  File "/usr/local/lib/python3.12/site-packages/alexapy/helpers.py", line 137, in wrapper
    return await func(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/alexapy/alexaapi.py", line 434, in run_behavior
    await self._post_request("/api/behaviors/preview", data=data)
  File "/usr/local/lib/python3.12/site-packages/alexapy/alexaapi.py", line 226, in _post_request
    return await self._request("post", uri, data, query)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/backoff/_async.py", line 151, in retry
    ret = await target(*args, **kwargs)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/alexapy/alexaapi.py", line 199, in _request
    raise AlexapyLoginError("Login error detected; not contacting API")
alexapy.errors.AlexapyLoginError: Login error detected; not contacting API

Warning 2:

Registrador: alexapy.helpers
Fuente: runner.py:190
Ocurrió por primera vez: 19:22:46 (3 ocurrencias)
Último inicio de sesión: 19:22:46

alexaapi.run_behavior((<alexapy.alexaapi.AlexaAPI object at 0x7fbdb9791460>, {'@type': 'com.amazon.alexa.behaviors.model.OpaquePayloadOperationNode', 'type': 'Alexa.Speak', 'operationPayload': {'deviceType': 'A3RBAYBE7VM004', 'deviceSerialNumber': 'G************30N', 'locale': 'es-es', 'customerId': 'A*****************VKG', 'textToSpeak': 'La temperatura de jardín es de 27.1 grados.', 'target': {'customerId': 'A*****************VKG', 'devices': [{'deviceSerialNumber': 'G************30N', 'deviceTypeId': 'A3RBAYBE7VM004'}]}, 'skillId': 'amzn1.ask.1p.saysomething'}}), {'queue_delay': 1.5}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments: ('Login error detected; not contacting API',)
alexaapi.send_sequence((<alexapy.alexaapi.AlexaAPI object at 0x7fbdb9791460>, 'Alexa.Speak'), {'customer_id': 'A*****************VKG', 'textToSpeak': 'La temperatura de jardín es de 27.1 grados.', 'target': {'customerId': 'A*****************VKG', 'devices': [{'deviceSerialNumber': 'G************30N', 'deviceTypeId': 'A3RBAYBE7VM004'}]}, 'skillId': 'amzn1.ask.1p.saysomething', 'queue_delay': 1.5}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments: ('Login error detected; not contacting API',)
alexaapi.send_tts((<alexapy.alexaapi.AlexaAPI object at 0x7fbdb9791460>, 'La temperatura de jardín es de 27.1 grados.'), {'customer_id': 'A*****************VKG', 'queue_delay': 1.5}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments: ('Login error detected; not contacting API',)

Warning 3:

Este error se originó a partir de una integración personalizada.

Registrador: alexapy.helpers
Fuente: custom_components/alexa_media/__init__.py:786
integración: Alexa Media Player (documentación, problemas)
Ocurrió por primera vez: 19:20:43 (6 ocurrencias)
Último inicio de sesión: 19:22:43

alexaapi.get_customer_history_records((<alexapy.alexalogin.AlexaLogin object at 0x7fbdb7a34a70>,), {'max_record_size': 10}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments: ('Unauthorized',)
alexaapi.get_last_device_serial((<alexapy.alexalogin.AlexaLogin object at 0x7fbdb7a34a70>,), {}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments: ('Unauthorized',)
alexaapi.get_customer_history_records((<alexapy.alexalogin.AlexaLogin object at 0x7fbdb7a34a70>,), {'max_record_size': 10}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments: ('Login error detected; not contacting API',)
alexaapi.get_last_device_serial((<alexapy.alexalogin.AlexaLogin object at 0x7fbdb7a34a70>,), {}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments: ('Login error detected; not contacting API',)

Then I reloaded the integration and I got the following errors at log.

Error 1:

Registrador: homeassistant.config_entries
Fuente: config_entries.py:819
Ocurrió por primera vez: 19:35:47 (2 ocurrencias)
Último inicio de sesión: 19:36:27

Error unloading entry Alexa for notify
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/config_entries.py", line 819, in async_unload
    result = await component.async_unload_entry(hass, self)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/components/notify/__init__.py", line 135, in async_unload_entry
    return await component.async_unload_entry(entry)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/helpers/entity_component.py", line 202, in async_unload_entry
    raise ValueError("Config entry was never loaded!")
ValueError: Config entry was never loaded!

Error 2:

Este error se originó a partir de una integración personalizada.

Registrador: alexapy.helpers
Fuente: custom_components/alexa_media/alexa_entity.py:336
integración: Alexa Media Player (documentación, problemas)
Ocurrió por primera vez: 19:36:20 (1 ocurrencias)
Último inicio de sesión: 19:36:20

alexaapi.get_entity_state((<alexapy.alexalogin.AlexaLogin object at 0x7fbdb6136060>,), {'entity_ids': ['*** edited ***']}): Timeout error occurred accessing AlexaAPI: An exception of type CancelledError occurred. Arguments: ()

It's impossible for me to help you troubleshoot your issue without seeing your related DEBUG logs...

image

@danielbrunt57
Copy link
Collaborator Author

This is the code in the api _request call:

    async def _request(
        self,
        method: str,
        uri: str,
        data: Optional[dict[str, str]] = None,
        query: Optional[dict[str, str]] = None,
    ) -> ClientResponse:
        async with self._login._oauth_lock:
            if self._login.expires_in and (self._login.expires_in - time.time() < 0):
                _LOGGER.debug(
                    "%s: Detected access token expiration; refreshing",
                    hide_email(self._login.email),
                )
                if (
                    # await self._login.get_tokens()
                    # and
                    await self._login.refresh_access_token()
                    and await self._login.exchange_token_for_cookies()
                    and await self._login.get_csrf()
                ):
                    await self._login.save_cookiefile()
                else:
                    _LOGGER.debug(
                        "%s: Unable to refresh oauth",
                        hide_email(self._login.email),
                    )
                    self._login.access_token = None
                    self._login.refresh_token = None
                    self._login.expires_in = None
        if method == "get":
            if query and not query.get("_"):
                query["_"] = math.floor(time.time() * 1000)
            elif query is None:
                query = {"_": math.floor(time.time() * 1000)}
        url: URL = URL(self._url + uri).update_query(query)
        _LOGGER.debug(
            "%s: Trying %s: %s : with uri: %s data %s query %s",
            hide_email(self._login.email),
            method,
            url,
            uri,
            data,
            query,
        )
        if self._login.close_requested:
            _LOGGER.debug(
                "%s: Login object has been asked to close; ignoring %s request to %s with %s %s",
                hide_email(self._login.email),
                method,
                uri,
                data,
                query,
            )
            raise AlexapyLoginCloseRequested()
        if not self._login.status.get("login_successful"):
            _LOGGER.debug(
                "%s:Login error detected; ignoring %s request to %s with %s %s",
                hide_email(self._login.email),
                method,
                uri,
                data,
                query,
            )
            raise AlexapyLoginError("Login error detected; not contacting API")
        if self._session.closed:
            raise AlexapyLoginError("Session is closed")
        response = await getattr(self._session, method)(
            url,
            json=data,
            # cookies=self._login._cookies,
            headers=self._login._headers,
            ssl=self._login._ssl,
        )
        _LOGGER.debug(
            "%s: %s: %s returned %s:%s:%s",
            hide_email(self._login.email),
            response.request_info.method,
            response.request_info.url,
            response.status,
            response.reason,
            response.content_type,
        )
        return await self._process_response(response, self._login)

@danielbrunt57
Copy link
Collaborator Author

It's really going to take someone who has the issue and also has somewhat expert debugging skills to get to the crux of the problem...

@JackTalisker
Copy link

JackTalisker commented Aug 25, 2024

This is the HA debug log chunk when AMP started malfunctioning, don't know if it helps.

2024-08-25 15:01:31.863 DEBUG (MainThread) [alexapy.alexaapi] c************e@y********m: static GET: https://alexa.amazon.it/api/notifications returned 200:OK:application/json
2024-08-25 15:01:31.897 DEBUG (MainThread) [custom_components.alexa_media] c************e@y********m: Updated 9 notifications for 5 devices at 2024-08-25 15:01:31.896977+02:00
2024-08-25 15:01:32.050 DEBUG (MainThread) [alexapy.alexaapi] c************e@y********m: static GET: https://www.amazon.it/alexa-privacy/apd/rvh/customer-history-records?startTime=1724504491897&endTime=1724677291897&recordType=VOICE_HISTORY&maxRecordSize=10 returned 401:Unauthorized:text/html
2024-08-25 15:01:32.051 WARNING (MainThread) [alexapy.helpers] alexaapi.get_customer_history_records((<alexapy.alexalogin.AlexaLogin object at 0x7f6faf35da00>,), {'max_record_size': 10}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments:
('Unauthorized',)
2024-08-25 15:01:32.051 WARNING (MainThread) [alexapy.helpers] alexaapi.get_last_device_serial((<alexapy.alexalogin.AlexaLogin object at 0x7f6faf35da00>,), {}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments:
('Unauthorized',)
2024-08-25 15:01:32.051 DEBUG (MainThread) [custom_components.alexa_media] Ovunque: DND False
2024-08-25 15:01:32.052 DEBUG (MainThread) [custom_components.alexa_media.media_player] c************e@y********m: Refreshing <entity media_player.ovunque=standby>
2024-08-25 15:01:32.052 DEBUG (MainThread) [custom_components.alexa_media.media_player] c************e@y********m: Ovunque: Last_called check: self: 7****************************207 reported: G************21H
2024-08-25 15:01:32.052 DEBUG (MainThread) [custom_components.alexa_media] Echo Show in cucina: Locale it-it timezone Europe/Paris
2024-08-25 15:01:32.052 DEBUG (MainThread) [custom_components.alexa_media] Echo Show in cucina: DND False
2024-08-25 15:01:32.052 DEBUG (MainThread) [custom_components.alexa_media.media_player] c************e@y********m: Refreshing <entity media_player.echo_show_in_cucina=standby>
2024-08-25 15:01:32.053 DEBUG (MainThread) [custom_components.alexa_media.media_player] c************e@y********m: Echo Show in cucina: Last_called check: self: G************07T reported: G************21H
2024-08-25 15:01:32.053 DEBUG (MainThread) [custom_components.alexa_media] Piano di sotto: DND False
2024-08-25 15:01:32.053 DEBUG (MainThread) [custom_components.alexa_media.media_player] c************e@y********m: Refreshing <entity media_player.piano_di_sotto=standby>
2024-08-25 15:01:32.053 DEBUG (MainThread) [custom_components.alexa_media.media_player] c************e@y********m: Piano di sotto: Last_called check: self: 3****************************a6b reported: G************21H
2024-08-25 15:01:32.053 DEBUG (MainThread) [custom_components.alexa_media] Dot Jolly: Locale it-it timezone Europe/Rome
2024-08-25 15:01:32.054 DEBUG (MainThread) [custom_components.alexa_media] Dot Jolly: DND False
2024-08-25 15:01:32.054 DEBUG (MainThread) [custom_components.alexa_media] Upstick: Locale it-it timezone Europe/Rome
2024-08-25 15:01:32.054 DEBUG (MainThread) [custom_components.alexa_media] Upstick: DND False
2024-08-25 15:01:32.054 DEBUG (MainThread) [custom_components.alexa_media.media_player] c************e@y********m: Refreshing <entity media_player.upstick=standby>
2024-08-25 15:01:32.054 DEBUG (MainThread) [custom_components.alexa_media.media_player] c************e@y********m: Upstick: Last_called check: self: G************WL3 reported: G************21H
2024-08-25 15:01:32.055 DEBUG (MainThread) [custom_components.alexa_media] Echo Show in salone: Locale it-it timezone Europe/Paris
2024-08-25 15:01:32.055 DEBUG (MainThread) [custom_components.alexa_media] Echo Show in salone: DND False
2024-08-25 15:01:32.055 DEBUG (MainThread) [custom_components.alexa_media.media_player] c************e@y********m: Refreshing <entity media_player.echo_show_in_salone=standby>
2024-08-25 15:01:32.055 DEBUG (MainThread) [custom_components.alexa_media.media_player] c************e@y********m: Echo Show in salone: Last_called check: self: G************21H reported: G************21H
2024-08-25 15:01:32.055 DEBUG (MainThread) [custom_components.alexa_media] Dot in studio: Locale it-it timezone Europe/Rome
2024-08-25 15:01:32.055 DEBUG (MainThread) [custom_components.alexa_media] Dot in studio: DND False
2024-08-25 15:01:32.056 DEBUG (MainThread) [custom_components.alexa_media] Piano di sopra: DND False
2024-08-25 15:01:32.056 DEBUG (MainThread) [custom_components.alexa_media.media_player] c************e@y********m: Refreshing <entity media_player.piano_di_sopra=standby>
2024-08-25 15:01:32.056 DEBUG (MainThread) [custom_components.alexa_media.media_player] c************e@y********m: Piano di sopra: Last_called check: self: 3****************************f14 reported: G************21H
2024-08-25 15:01:32.056 DEBUG (MainThread) [custom_components.alexa_media] Dot in bagno: Locale it-it timezone Europe/Paris
2024-08-25 15:01:32.056 DEBUG (MainThread) [custom_components.alexa_media] Dot in bagno: DND False
2024-08-25 15:01:32.056 DEBUG (MainThread) [custom_components.alexa_media.media_player] c************e@y********m: Refreshing <entity media_player.echo_dot_di_gherardo=standby>
2024-08-25 15:01:32.057 DEBUG (MainThread) [custom_components.alexa_media.media_player] c************e@y********m: Dot in bagno: Last_called check: self: G************4BB reported: G************21H
2024-08-25 15:01:32.057 DEBUG (MainThread) [custom_components.alexa_media] Echo Plus  in camera da letto: Locale it-it timezone Europe/Rome
2024-08-25 15:01:32.057 DEBUG (MainThread) [custom_components.alexa_media] Echo Plus  in camera da letto: DND False
2024-08-25 15:01:32.057 DEBUG (MainThread) [custom_components.alexa_media.media_player] c************e@y********m: Refreshing <entity media_player.echo_plus_in_camera_da_letto=standby>
2024-08-25 15:01:32.057 DEBUG (MainThread) [custom_components.alexa_media.media_player] c************e@y********m: Echo Plus  in camera da letto: Last_called check: self: G************3Q6 reported: G************21H
2024-08-25 15:01:32.057 DEBUG (MainThread) [custom_components.alexa_media] LG: Locale it-it timezone Europe/Rome
2024-08-25 15:01:32.057 DEBUG (MainThread) [custom_components.alexa_media] LG: DND False
2024-08-25 15:01:32.058 DEBUG (MainThread) [custom_components.alexa_media] Salastick: Locale it-it timezone Europe/Rome
2024-08-25 15:01:32.058 DEBUG (MainThread) [custom_components.alexa_media] Salastick: DND False
2024-08-25 15:01:32.058 DEBUG (MainThread) [custom_components.alexa_media.media_player] c************e@y********m: Refreshing <entity media_player.salastick=standby>
2024-08-25 15:01:32.058 DEBUG (MainThread) [custom_components.alexa_media.media_player] c************e@y********m: Salastick: Last_called check: self: G************0MH reported: G************21H
2024-08-25 15:01:32.058 DEBUG (MainThread) [custom_components.alexa_media] This Device: Locale it-it timezone Europe/Rome
2024-08-25 15:01:32.058 DEBUG (MainThread) [custom_components.alexa_media] This Device: DND False
2024-08-25 15:01:32.059 DEBUG (MainThread) [custom_components.alexa_media.media_player] c************e@y********m: Refreshing <entity media_player.this_device=standby>
2024-08-25 15:01:32.059 DEBUG (MainThread) [custom_components.alexa_media.media_player] c************e@y********m: This Device: Last_called check: self: 3****************************5da reported: G************21H
2024-08-25 15:01:32.059 DEBUG (MainThread) [custom_components.alexa_media] c************e@y********m: Existing: [<entity media_player.ovunque=standby>, <entity media_player.echo_show_in_cucina=standby>, <entity media_player.piano_di_sotto=standby>, <entity media_player.dot_in_bagno=unavailable>, <entity media_player.upstick=standby>, <entity media_player.echo_show_in_salone=standby>, <entity media_player.dot_in_mansarda=unavailable>, <entity media_player.piano_di_sopra=standby>, <entity media_player.echo_dot_di_gherardo=standby>, <entity media_player.echo_plus_in_camera_da_letto=standby>, <entity media_player.gherardo_s_lg_webos_2022_tv=unavailable>, <entity media_player.salastick=standby>, <entity media_player.this_device=standby>] New: []; Filtered out by not being in include: [] or in exclude: []
2024-08-25 15:01:32.065 DEBUG (MainThread) [custom_components.alexa_media] Finished fetching alexa_media data in 5.004 seconds (success: True)

@figorr
Copy link

figorr commented Aug 25, 2024

Just for if it helps.

I enabled the debug registry from AMP and then I restarted HA.

So this is the log since the restart until it fails.

I edited serial numbers, email, ...

I did the test after updating to Core 2024.8.3, released today.

alexa_media_player_debug_log.txt

@NdR91
Copy link

NdR91 commented Aug 26, 2024

I tried the suggested workaround changing the const.py, but after the reboot i receive a "bad configuration" notification from HA with this error log:

Detected blocking call to import_module with args ('custom_components.alexa_media',) in /usr/src/homeassistant/homeassistant/loader.py, line 1067: ComponentProtocol, importlib.import_module(self.pkg_path) inside the event loop; This is causing stability issues. Please create a bug report at https://github.com/home-assistant/core/issues?q=is%3Aopen+is%3Aissue For developers, please see https://developers.home-assistant.io/docs/asyncio_blocking_operations/#import_module Traceback (most recent call last): File "", line 198, in _run_module_as_main File "", line 88, in _run_code File "/usr/src/homeassistant/homeassistant/main.py", line 223, in sys.exit(main()) File "/usr/src/homeassistant/homeassistant/main.py", line 209, in main exit_code = runner.run(runtime_conf) File "/usr/src/homeassistant/homeassistant/runner.py", line 190, in run return loop.run_until_complete(setup_and_run_hass(runtime_config)) File "/usr/local/lib/python3.12/asyncio/base_events.py", line 674, in run_until_complete self.run_forever() File "/usr/local/lib/python3.12/asyncio/base_events.py", line 641, in run_forever self._run_once() File "/usr/local/lib/python3.12/asyncio/base_events.py", line 1990, in _run_once handle._run() File "/usr/local/lib/python3.12/asyncio/events.py", line 88, in _run self._context.run(self._callback, *self._args) File "/usr/src/homeassistant/homeassistant/setup.py", line 165, in async_setup_component result = await _async_setup_component(hass, domain, config) File "/usr/src/homeassistant/homeassistant/setup.py", line 334, in _async_setup_component component = await integration.async_get_component() File "/usr/src/homeassistant/homeassistant/loader.py", line 1019, in async_get_component comp = self._get_component() File "/usr/src/homeassistant/homeassistant/loader.py", line 1067, in _get_component ComponentProtocol, importlib.import_module(self.pkg_path)

@JackTalisker
Copy link

Here is a complete debug log
AMP debug log.txt

@monat78
Copy link

monat78 commented Aug 26, 2024

image

In .es always reconfigure

@jleinenbach
Copy link

jleinenbach commented Aug 26, 2024

I just tried again as it works for me.

Core 2024.9.0.dev202408260813
Frontend 20240826.0.dev
AMP 4.12.11

Manually changed the manifest.json to alexapy 1.29.0
Checked and fixed the python dependencies with pip.

Result:
alexapy 1.29.0 has requirement aiofiles<24.0.0,>=23.1.0, but you have aiofiles 24.1.0.

Reboot HA.

New configuration:

  • amazon.de
  • 90s instead of 60s
  • all URLs with / at the end
  • no includes, no excludes
  • popup message with OTP: This was the one as seen on my OTP app
  • browser opened
    • I was asked for a captcha several times although I had no typos
    • login as usual
    • OTP was prefilled, but obsolete, used a new one
    • checkmark to remember the browser

TTS works, switching the "do not disturb" switch does not.
image

2024-08-26 16:03:13.225 DEBUG (MainThread) [alexapy.alexahttp2] Starting message parsing loop.
2024-08-26 16:03:13.225 DEBUG (MainThread) [alexapy.alexahttp2] Connecting to https://alexa.eu.gateway.devices.a2z.com/v20160207/directives with {'method': 'GET', 'path': '/v20160207/directives', 'authority': 'alexa.eu.gateway.devices.a2z.com', 'scheme': 'https', 'authorization': 'Bearer ...'}
2024-08-26 16:03:13.226 DEBUG (MainThread) [alexapy.alexahttp2] Preparing ping to https://alexa.eu.gateway.devices.a2z.com/ping
2024-08-26 16:03:13.396 DEBUG (MainThread) [alexapy.alexaapi] j*************h@g*******m: static GET: https://alexa.amazon.de/api/bootstrap returned 200:OK:application/json
2024-08-26 16:03:13.406 DEBUG (MainThread) [alexapy.alexaapi] j*************h@g*******m: static GET: https://alexa.amazon.de/api/devices-v2/device returned 200:OK:application/json
2024-08-26 16:03:13.446 DEBUG (MainThread) [alexapy.alexahttp2] Received raw message: --------abcde123

2024-08-26 16:03:13.480 DEBUG (MainThread) [alexapy.alexaapi] j*************h@g*******m: static GET: https://alexa.amazon.de/api/dnd/device-status-list returned 200:OK:application/json
2024-08-26 16:03:13.493 DEBUG (MainThread) [alexapy.alexahttp2] Received response: 204:
2024-08-26 16:03:13.638 DEBUG (MainThread) [alexapy.alexaapi] j*************h@g*******m: static GET: https://alexa.amazon.de/api/device-preferences returned 200:OK:application/json
2024-08-26 16:03:13.640 DEBUG (MainThread) [alexapy.alexaapi] j*************h@g*******m: static GET: https://alexa.amazon.de/api/bluetooth?cached=false returned 200:OK:application/json
2024-08-26 16:03:13.675 DEBUG (MainThread) [alexapy.alexaapi] j*************h@g*******m: static GET: https://alexa.amazon.de/api/phoenix returned 200:OK:application/json

@matteorossininchi
Copy link

matteorossininchi commented Aug 27, 2024

Hi,

System details

Home Assistant version: 2024.8.3
alexa_media version: 4.12.11
alexapy version (from pip show alexapy in homeasssistant container or HA startup log): 1.29
Is Amazon [2FA/2SV enabled]): Yes
Amazon Domain: .it

I changed the values in const.py as in the original post.

The integration is working pretty decent, I don't have to reauthenticate every 10 minutes like some days ago.
If I don't "play" too much with TTS and update_last_called, it works.

I'm not a programmer or anything, just trying to understand so maybe what I write has no sense or is normal...
What I found now is that AMP was not able to login anymore for some time, than it started working again but the "reauthenticate" message appeared in home assistant (check log below).
Even though "reauthenticate" message is still there, if I just reload the integration it works. I don't need to do the authentication procedure.the TTS is working or at least not giving errors in the log (I'm not at home to hear if the TTS worked).
update_last_called still doesn't work, the sensor is not updated.
I just get the log
2024-08-27 11:40:48.595 DEBUG (MainThread) [custom_components.alexa_media.services] Service update_last_called for: []

2024-08-27 11:22:10.809 DEBUG (MainThread) [custom_components.alexa_media.helpers] alexa_media.media_player.refresh: detected bad login for s*****0@h********t: An exception of type AlexapyLoginError occurred. Arguments:
('Login error detected; not contacting API',)
2024-08-27 11:22:10.809 DEBUG (MainThread) [custom_components.alexa_media.helpers] Reporting need to relogin to amazon.it with s*****0@h********t stats: {'login_timestamp': datetime.datetime(2024, 8, 27, 11, 19, 27, 153377), 'api_calls': 22}
2024-08-27 11:22:10.810 DEBUG (MainThread) [custom_components.alexa_media] s*****0@h********t: Received relogin request: <Event alexa_media_relogin_required[L]: email=s*****0@h********t, url=amazon.it, stats=login_timestamp=2024-08-27T11:19:27.153377+02:00, api_calls=22>
2024-08-27 11:22:10.811 DEBUG (MainThread) [custom_components.alexa_media.helpers] s*****0@h********t: Returning uuid {'uuid': '051b68318db52310ca72e00409c9b9bc', 'index': 0}
2024-08-27 11:22:10.818 DEBUG (MainThread) [custom_components.alexa_media] s*****0@h********t: Received relogin request: <Event alexa_media_relogin_required[L]: email=s*****0@h********t, url=amazon.it, stats=login_timestamp=2024-08-27T11:19:27.153377+02:00, api_calls=22>
2024-08-27 11:22:10.818 DEBUG (MainThread) [custom_components.alexa_media.helpers] s*****0@h********t: Returning uuid {'uuid': '051b68318db52310ca72e00409c9b9bc', 'index': 0}
2024-08-27 11:22:10.824 DEBUG (MainThread) [custom_components.alexa_media] Testing login status: {}
2024-08-27 11:22:10.824 DEBUG (MainThread) [custom_components.alexa_media] Logging in: {'otp_secret': '4************************************************3BA', 'email': 's*****0@h********t', 'password': 'REDACTED 16 CHARS', 'url': 'amazon.it', 'scan_interval': 600, 'include_devices': '', 'exclude_devices': 'This Device, Ovunque, Sonos Cucina, Sonos Soggiorno', 'debug': False, 'oauth': {'access_token': 'A*********kYA', 'refresh_token': 'A**********1BA', 'expires_in': 1724753196.050189, 'mac_dms': {'device_private_key': ****}'}, 'code_verifier': '***', 'authorization_code': '***'}, 'public_url': '', 'queue_delay': 1.5, 'extended_entity_discovery': False} set()
2024-08-27 11:22:10.825 DEBUG (MainThread) [custom_components.alexa_media] Login stats: {'login_timestamp': datetime.datetime(2024, 8, 27, 11, 19, 27, 153377), 'api_calls': 22}
2024-08-27 11:22:10.825 DEBUG (MainThread) [custom_components.alexa_media] Creating new config flow to login
2024-08-27 11:22:10.838 DEBUG (MainThread) [custom_components.alexa_media.config_flow] Creating reauth form with OrderedDict({'otp_secret': '4************************************************3BA', 'email': 's*****0@h********t', 'password': 'REDACTED 16 CHARS', 'url': 'amazon.it', 'scan_interval': 600, 'include_devices': '', 'exclude_devices': 'This Device, Ovunque, Sonos Cucina, Sonos Soggiorno', 'debug': False, 'reauth': True})
2024-08-27 11:22:10.838 DEBUG (MainThread) [custom_components.alexa_media.config_flow] Attempting automatic relogin
2024-08-27 11:22:10.844 DEBUG (MainThread) [custom_components.alexa_media] Testing login status: {}
2024-08-27 11:22:10.844 DEBUG (MainThread) [custom_components.alexa_media] Logging in: {'otp_secret': '4************************************************3BA', 'email': 's*****0@h********t', 'password': 'REDACTED 16 CHARS', 'url': 'amazon.it', 'scan_interval': 600, 'include_devices': '', 'exclude_devices': 'This Device, Ovunque, Sonos Cucina, Sonos Soggiorno', 'debug': False, 'oauth': {'access_token': 'A********kYA', 'refresh_token': 'A*****1BA', 'expires_in': 1724753196.050189, 'mac_dms': {'device_private_key': '****}, 'code_verifier': '****', 'authorization_code': '****'}, 'public_url': '', 'queue_delay': 1.5, 'extended_entity_discovery': False} set()
2024-08-27 11:22:10.845 DEBUG (MainThread) [custom_components.alexa_media] Login stats: {'login_timestamp': datetime.datetime(2024, 8, 27, 11, 19, 27, 153377), 'api_calls': 22}
2024-08-27 11:22:10.845 DEBUG (MainThread) [custom_components.alexa_media] Creating new config flow to login
2024-08-27 11:22:10.847 DEBUG (MainThread) [custom_components.alexa_media.config_flow] Creating reauth form with OrderedDict({'otp_secret': '4************************************************3BA', 'email': 's*****0@h********t', 'password': 'REDACTED 16 CHARS', 'url': 'amazon.it', 'scan_interval': 600, 'include_devices': '', 'exclude_devices': 'This Device, Ovunque, Sonos Cucina, Sonos Soggiorno', 'debug': False, 'reauth': True})
2024-08-27 11:22:10.847 DEBUG (MainThread) [custom_components.alexa_media.config_flow] Attempting automatic relogin
2024-08-27 11:22:12.309 ERROR (MainThread) [homeassistant] Error doing job: Task exception was never retrieved (None)
Traceback (most recent call last):
  File "/usr/local/lib/python3.12/site-packages/alexapy/helpers.py", line 137, in wrapper
    return await func(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/alexapy/alexaapi.py", line 584, in run_custom
    await self.send_sequence(
  File "/usr/local/lib/python3.12/site-packages/alexapy/helpers.py", line 137, in wrapper
    return await func(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/alexapy/alexaapi.py", line 512, in send_sequence
    await self.run_behavior(node_data, queue_delay=queue_delay)
  File "/usr/local/lib/python3.12/site-packages/alexapy/helpers.py", line 137, in wrapper
    return await func(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/alexapy/alexaapi.py", line 434, in run_behavior
    await self._post_request("/api/behaviors/preview", data=data)
  File "/usr/local/lib/python3.12/site-packages/alexapy/alexaapi.py", line 226, in _post_request
    return await self._request("post", uri, data, query)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/backoff/_async.py", line 151, in retry
    ret = await target(*args, **kwargs)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/alexapy/alexaapi.py", line 199, in _request
    raise AlexapyLoginError("Login error detected; not contacting API")
alexapy.errors.AlexapyLoginError: Login error detected; not contacting API
2024-08-27 11:22:25.841 DEBUG (MainThread) [custom_components.alexa_media.config_flow] Using existing login
2024-08-27 11:22:25.841 DEBUG (MainThread) [custom_components.alexa_media.config_flow] Trying to login {}
2024-08-27 11:22:25.849 DEBUG (MainThread) [custom_components.alexa_media.config_flow] Using existing login
2024-08-27 11:22:25.850 DEBUG (MainThread) [custom_components.alexa_media.config_flow] Trying to login {}
2024-08-27 11:22:29.010 DEBUG (MainThread) [custom_components.alexa_media.config_flow] Testing login status: {'login_successful': True}
2024-08-27 11:22:29.011 DEBUG (MainThread) [custom_components.alexa_media.config_flow] Reauth successful for s*****0@h********t
2024-08-27 11:22:29.011 DEBUG (MainThread) [custom_components.alexa_media] Received Login success: <Event alexa_media_relogin_success[L]: email=s*****0@h********t, url=amazon.it>

@jleinenbach
Copy link

  • Login Attempts and Reauthentications:
    The logs show repeated attempts to log into Amazon. Notably, after a successful login at 2024-08-27 11:19:27.153377, a "bad login" is detected again within a few minutes (2024-08-27 11:22:10.809). This suggests that the integration repeatedly tried to access the API, which may have been perceived as suspicious by Amazon, necessitating reauthentication.

  • Multiple Error Messages:
    The repeated error messages, particularly the AlexapyLoginError, which indicates that a "login error was detected" and that the API is not being contacted, suggest that the integration is having trouble maintaining authentication. This could be due to making too frequent requests to the API, which Amazon might interpret as abuse.

  • API Call Patterns:
    Between the first and second relevant login attempts, approximately 2 minutes and 43 seconds elapsed during which 22 API calls were made. This relatively high number of requests in such a short time could be the reason Amazon interrupted the authentication to ensure that the user is legitimate. This could have been triggered by internal security features or rate limits that might exhibit similar behavior patterns as those in the better-documented AWS services.

In Summary:

  • Frequent API Calls and Authentication Errors:
    The logs show a pattern of frequent API calls and repeated authentication errors, indicating that the integration might be trying too aggressively to access the Amazon API.

  • Potential Rate Limits or Security Mechanisms:
    The repeated prompts for reauthentication could be a result of security features designed to prevent suspicious behavior or of implicit rate limits leading to throttling, as is the case with other Amazon APIs.

  • Possible Solutions:

    • Reduce API Call Frequency:
      It might be helpful to reduce the number of API calls and adopt less aggressive access patterns. This could prevent Amazon from flagging the requests as suspicious and requiring reauthentication.
    • Adjust Integration Settings:
      We should consider adjusting the integration settings to generate fewer API calls, thereby minimizing the likelihood of triggering rate limits or security measures.

@serlinGi
Copy link

  • Login Attempts and Reauthentications:
    The logs show repeated attempts to log into Amazon. Notably, after a successful login at 2024-08-27 11:19:27.153377, a "bad login" is detected again within a few minutes (2024-08-27 11:22:10.809). This suggests that the integration repeatedly tried to access the API, which may have been perceived as suspicious by Amazon, necessitating reauthentication.
  • Multiple Error Messages:
    The repeated error messages, particularly the AlexapyLoginError, which indicates that a "login error was detected" and that the API is not being contacted, suggest that the integration is having trouble maintaining authentication. This could be due to making too frequent requests to the API, which Amazon might interpret as abuse.
  • API Call Patterns:
    Between the first and second relevant login attempts, approximately 2 minutes and 43 seconds elapsed during which 22 API calls were made. This relatively high number of requests in such a short time could be the reason Amazon interrupted the authentication to ensure that the user is legitimate. This could have been triggered by internal security features or rate limits that might exhibit similar behavior patterns as those in the better-documented AWS services.

In Summary:

  • Frequent API Calls and Authentication Errors:
    The logs show a pattern of frequent API calls and repeated authentication errors, indicating that the integration might be trying too aggressively to access the Amazon API.

  • Potential Rate Limits or Security Mechanisms:
    The repeated prompts for reauthentication could be a result of security features designed to prevent suspicious behavior or of implicit rate limits leading to throttling, as is the case with other Amazon APIs.

  • Possible Solutions:

    • Reduce API Call Frequency:
      It might be helpful to reduce the number of API calls and adopt less aggressive access patterns. This could prevent Amazon from flagging the requests as suspicious and requiring reauthentication.
    • Adjust Integration Settings:
      We should consider adjusting the integration settings to generate fewer API calls, thereby minimizing the likelihood of triggering rate limits or security measures.

OK, all correct!
but then why doesn't this happen with the July version of HA??

@scorbacella
Copy link

Hi, I just changed the scan interval to 3600. It's working despite I immediately got this error:

2024-08-27 13:59:48.076 ERROR (MainThread) [homeassistant.config_entries] Error unloading entry ***.*****@.com - amazon.it for notify
Traceback (most recent call last):
File "/usr/src/homeassistant/homeassistant/config_entries.py", line 819, in async_unload
result = await component.async_unload_entry(hass, self)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/src/homeassistant/homeassistant/components/notify/init.py", line 135, in async_unload_entry
return await component.async_unload_entry(entry)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/src/homeassistant/homeassistant/helpers/entity_component.py", line 202, in async_unload_entry
raise ValueError("Config entry was never loaded!")
ValueError: Config entry was never loaded!

What does it mean?

Before 3600 it was 600 secs and AMP worked for a day.

AMP 4.12.11
core 2024.08.2

@danielbrunt57
Copy link
Collaborator Author

image

In .es always reconfigure

I can't help as I don't use .es...

@danielbrunt57
Copy link
Collaborator Author

switching the "do not disturb" switch does not.

This sounds like http2 is not connected...

@jleinenbach
Copy link

jleinenbach commented Aug 27, 2024

OK, all correct! but then why doesn't this happen with the July version of HA??

Perhaps there are bugs in the dependent Python libraries, and Home Assistant 2024.8.x is using exactly those buggy versions.

I have a developer version of HA: 2024.9.x.DEV
Here I attached my requirements.txt

It's not possible to install it with:
pip install -r requirements.txt

I get:

The conflict is caused by:
The user requested aiofiles==24.1.0
alexapy 1.29.0 depends on aiofiles<24.0.0 and >=23.1.0

But it's possible to overwrite this with, but you shouldn't do it unless you know how to roll back if it breaks:
pip install --no-deps -r requirements.txt

But maybe it's useful to compare the library versions?

You can get this list with:
pip install pipdeptree
pipdeptree --packages alexapy --freeze > requirements.txt
pipdeptree --packages wrapt --freeze >> requirements.txt
pipdeptree --packages packaging --freeze >> requirements.txt

@jleinenbach
Copy link

jleinenbach commented Aug 27, 2024

Hi, I just changed the scan interval to 3600. It's working despite I immediately got this error:
... entry was never loaded!") ValueError: Config entry was never loaded!

What does it mean?

Before 3600 it was 600 secs and AMP worked for a day.

AMP 4.12.11 core 2024.08.2

Oh? I had this issue after an HA upgrade, too. Nonetheless, the integration still worked. I removed the configuration and created a new one, then I could reload without this error.

@danielbrunt57
Copy link
Collaborator Author

update_last_called still doesn't work, the sensor is not updated.

Yes, Amazon ceased issuing the command "PUSH_ACTIVITY" via http2push back in June which negated AMP's ability to automatically update LAST_ALEXA via that command.

@danielbrunt57
Copy link
Collaborator Author

Hi, I just changed the scan interval to 3600. It's working despite I immediately got this error:

2024-08-27 13:59:48.076 ERROR (MainThread) [homeassistant.config_entries] Error unloading entry .@**.com - amazon.it for notify Traceback (most recent call last): File "/usr/src/homeassistant/homeassistant/config_entries.py", line 819, in async_unload result = await component.async_unload_entry(hass, self) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/src/homeassistant/homeassistant/components/notify/init.py", line 135, in async_unload_entry return await component.async_unload_entry(entry) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/src/homeassistant/homeassistant/helpers/entity_component.py", line 202, in async_unload_entry raise ValueError("Config entry was never loaded!") ValueError: Config entry was never loaded!

What does it mean?

Before 3600 it was 600 secs and AMP worked for a day.

AMP 4.12.11 core 2024.08.2

You can safely disregard that error as it would seem to be irrelevant. I've witnessed trying to unload a config entry that was never loaded but when I try and troubleshoot the reason then it doesn't happen! If it tries to unload a config entry that isn't loaded it should silently proceed, or maybe issue a warning, but not an error! If I could pinpoint it, I'd try and fix it!

@serlinGi
Copy link

Hi, I just changed the scan interval to 3600. It's working despite I immediately got this error:
... entry was never loaded!") ValueError: Config entry was never loaded!
What does it mean?
Before 3600 it was 600 secs and AMP worked for a day.
AMP 4.12.11 core 2024.08.2

Oh? I had this issue after an HA upgrade, too. Nonetheless, the integration still worked. I removed the configuration and created a new one, then I could reload without this error.

unfortunately I am not able to give this kind of collaboration. I chose to install OS of HA precisely because I am not able to manage, I'm really sorry 😭

@danielbrunt57
Copy link
Collaborator Author

danielbrunt57 commented Aug 27, 2024

I have been inside AMP for a while now attempting to dissect it, and comparing it to other "standard" integrations is difficult as nothing else seems to try and do what AMP does, and nothing else is structured quite the way AMP is.
Also, my overall understanding of all the HA python workings is still very limited and to illustrate, I was bothered by the fact that http2connect was remaining active after removing the integration config entry. Removing it should have terminated the http2 connection but didn't. I analyzed the code flow for hours and finally inserted a _LOGGER.debug statement to try and see what was going on, removed the config entry, restarted to implement my code addition, re-added config entry and then removed it. My debug line logged my message Connections closed: True and a check of debug messages for http2 showed that http had ceased this time! So it would seem that my simple addition of the _LOGGER.debug statement somehow allowed the connection to close and log my message. Why? It's beyond my current HA debug abilities of HA to figure out, despite my 35+ years in computer technology programming and debugging!

@danielbrunt57
Copy link
Collaborator Author

unfortunately I am not able to give this kind of collaboration. I chose to install OS of HA precisely because I am not able to manage, I'm really sorry

No worries, thanks!

@Destroyer061090
Copy link

hello,

not clear if someone solve the issues. I have done following change but without good result:
In const.py, try editing these constants as follows:
From:

SCAN_INTERVAL = timedelta(seconds=60)
MIN_TIME_BETWEEN_FORCED_SCANS = timedelta(seconds=1)
DEFAULT_SCAN_INTERVAL = 60

To:

SCAN_INTERVAL = timedelta(seconds=180)
MIN_TIME_BETWEEN_FORCED_SCANS = timedelta(seconds=5)
DEFAULT_SCAN_INTERVAL = 300

the reconfiguration pop up appears continuously:
image

just after the HA restart this is the situation:
image

@voyagerft
Copy link

hello,

not clear if someone solve the issues. I have done following change but without good result: In const.py, try editing these constants as follows: From:

SCAN_INTERVAL = timedelta(seconds=60)
MIN_TIME_BETWEEN_FORCED_SCANS = timedelta(seconds=1)
DEFAULT_SCAN_INTERVAL = 60

To:

SCAN_INTERVAL = timedelta(seconds=180)
MIN_TIME_BETWEEN_FORCED_SCANS = timedelta(seconds=5)
DEFAULT_SCAN_INTERVAL = 300

the reconfiguration pop up appears continuously: image

just after the HA restart this is the situation: image

Hai risolto?

@jleinenbach
Copy link

Here is a complete debug log AMP debug log.txt

Analysis done by ChatGPT:

Detailed Chronological Analysis with Focus on Specific Behavior

1. Initialization and Start of the Login Process (09:54:08)

  • 09:54:08.282:

    • Event: The alexapy library is loaded, version 1.28.2.
    • Significance: This library provides the necessary functions for interacting with the Alexa API, forming the basis for the subsequent process.
  • 09:54:08.295:

    • Event: The login process for the user c************e@y********m on the amazon.it domain begins.
    • Action: The system searches for existing authentication cookies in the file /config/.storage/alexa_media.c************e@y********m.pickle to facilitate and speed up re-authentication.
    • Significance: Using stored cookies aims to enable a quick and seamless authentication without requiring a full re-login.
  • 09:54:08.309:

    • Event: Successfully loading 9 cookies.
    • Action: The system attempts to use these cookies for logging in to amazon.it.
    • Significance: A successful login would indicate that the stored authentication data is still valid.

2. Failed Registration Attempts (09:54:08 - 09:54:09)

  • 09:54:08.795:

    • Event: The attempt to register with amazon.it fails with a 401 Unauthorized error.
    • Details:
      • The request to https://api.amazon.it/auth/register was made using the loaded cookies and other authentication data.
      • The server responded with 401 Unauthorized, indicating that the provided authentication data was invalid or expired.
    • Significance: The system is unable to authenticate using the existing data and may require re-authentication or token renewal. This step clearly indicates that the stored authentication data is no longer valid.
  • 09:54:08.796:

    • Event: A second attempt to register with amazon.com also fails with a 401 Unauthorized error.
    • Details:
      • A similar process occurred as before, but this time with the domain amazon.com.
      • The same authentication data was used, which the server rejected.
    • Significance: The issue is not domain-specific but lies with the authentication data itself. This indicates a systemic problem with the credentials or tokens being used.
  • 09:54:09.295:

    • Event: The system logs the message Unable to register with ['amazon.it', 'amazon.com'].
    • Significance:
      • The system recognizes that both registration attempts failed and indicates that it was unable to register successfully.
      • This message should ideally trigger a process to handle the failed authentication, such as attempting to renew the tokens or halting further actions until valid authentication data is available.

3. Continuing with API Requests Despite Failed Registration (09:54:09 - 09:54:10)

  • 09:54:09.564:

    • Event: A request is sent to https://api.amazonalexa.com/v1/devices/@self/capabilities, receiving a 403 Forbidden response.
    • Behavior Analysis:
      • Immediate Continuation: Despite the previous error message, the system proceeds to make an API request.
      • Lack of Authentication: Given that the previous registration attempts failed, the system likely does not have valid authentication data, leading to the 403 Forbidden error.
    • Logic Question:
      • Is this behavior logical?: Under normal circumstances, the system should not proceed with further API requests after a failed registration, as they are likely to fail as well.
      • Possible Reasons:
        • Automatic Retry Mechanism: The system may have a built-in mechanism to attempt to continue despite errors, hoping that authentication will succeed at a later step.
        • Parallel Processes: It is possible that different parts of the system operate independently and are not sufficiently synchronized, leading to API requests being made before successful authentication is confirmed.
        • Error Handling Gaps: There may be gaps in error handling that cause the system to fail to respond correctly to error messages, continuing actions regardless.
    • Conclusion:
      • Recommendation: The system should be adjusted to better handle failed registrations by either halting API requests until authentication is successful or implementing a more robust synchronization process. This would prevent unnecessary errors and ensure that API calls are only made when the system is in a valid state to do so.
  • 09:54:09.950:

    • Event: The system logs 5 cookies successfully exchanged for refresh token for domain .amazon.it.
    • Significance:
      • The system attempts to update the existing cookies and exchange them for a new refresh token.
      • This is a positive step toward obtaining valid authentication data.
    • Analysis:
      • Timing Issue: This attempt to update the authentication data occurs after the failed API request, raising the question of whether this step should have been taken before further API calls were made.
    • Conclusion:
      • Recommendation: The sequencing of these steps should be reviewed and possibly adjusted to ensure that valid authentication data is always in place before API requests are sent. Proper sequencing would reduce errors and increase the reliability of the system's operations.
  • 09:54:10.693:

    • Event: Another request is sent to https://alexa.amazon.com/api/bootstrap, receiving a 401 Unauthorized error.
    • Analysis:
      • Continued Errors: Despite the previous attempt to update the authentication data, this request still fails.
      • Possible Causes:
        • Timing Delay: The token update might not have been fully completed or propagated when this request was made.
        • Invalid or Incomplete Update: The attempt to update the cookies may not have been successful, or the new data was not correctly utilized.
      • Logic Behind the Request:
        • Need for the Request: Sending a bootstrap request is a standard step to obtain basic information and settings. However, this should only be done if valid authentication data is available.
    • Conclusion:
      • Recommendation: The system should verify successful authentication before sending such requests and, if necessary, attempt re-authentication or delay the request. This would ensure that resources are only accessed when the system is properly authenticated, reducing the likelihood of encountering repeated errors.

4. Successful Authentication (09:54:10 - 09:54:11)

  • 09:54:10.914:

    • Event: The system successfully logs in to amazon.it (Logged in as c************e@y********m to amazon.it).
    • Significance:
      • After several failed attempts, the system finally succeeds in authenticating.
      • It is likely that the previous steps to update cookies and tokens eventually led to success.
    • Analysis:
      • Delayed Effectiveness: The successful authentication data may have become available only after some time, explaining the earlier failed attempts.
      • Synchronization Issues: This might indicate timing or synchronization problems within the system, where API requests are sent before authentication is fully completed.
    • Conclusion:
      • Recommendation: The system should be revised to ensure proper synchronization of processes and to confirm that valid authentication data is in place before proceeding with any API requests. This would ensure that actions are only taken when the system is fully prepared, avoiding unnecessary errors and improving overall efficiency.
  • 09:54:11.138:

    • Event: Confirmation of the successful login and saving of new authentication data (Login confirmed for...).
    • Significance:
      • The system now has valid and up-to-date authentication data, enabling successful API interactions moving forward.
      • This should provide the foundation for stable and error-free interactions with the Alexa API. Proper logging of this event ensures that the system is correctly tracking its state and ready for future operations.

@matteorossininchi
Copy link

I have polling currently disabled but AMP still stops working sometimes, showing auth response <ClientResponse(https://api.amazon.it/auth/register) [400 Bad Request]> when reloading the integration or [401 Unauthorized]

After days of testing I'm 99% sure that the issue is not related to Too many requests, at least in my case of course.

I tried TTS and update_last_called 11 times in around 30 minutes right after restarting HA. All worked, not a single issue.
I will try again this evening but I'm pretty sure I won't be able to get so much success when calling update_last_called... maybe I will be able to run 1 or 2 update_last_called before getting [401 Unauthorized] and having to restart HA.

Below is what happened during the night, of course nobody was doing anything...
Not sure why http2 was closed (at 02:45:32.712 ) and which autorization token was missing (02:45:32.979).
http2 was completely closed at 02:45:35.587 and never restarted.

2024-09-03 02:45:15.708 DEBUG (MainThread) [alexapy.alexahttp2] Preparing ping to https://alexa.eu.gateway.devices.a2z.com/ping
2024-09-03 02:45:15.768 DEBUG (MainThread) [alexapy.alexahttp2] Received response: 204:
2024-09-03 02:45:32.712 DEBUG (MainThread) [alexapy.alexahttp2] HTTP2 Connection Closed.
2024-09-03 02:45:32.714 DEBUG (MainThread) [custom_components.alexa_media] s*****0@h********t: HTTP2 push closed; reconnect #0 in 5s
2024-09-03 02:45:32.756 DEBUG (MainThread) [custom_components.alexa_media] s*****0@h********t: HTTP2 created: <alexapy.alexahttp2.HTTP2EchoClient object at 0x7f85faf080>
2024-09-03 02:45:32.757 DEBUG (MainThread) [custom_components.alexa_media] s*****0@h********t: HTTP2push successfully connected
2024-09-03 02:45:32.757 DEBUG (MainThread) [alexapy.alexahttp2] Starting message parsing loop.
2024-09-03 02:45:32.757 DEBUG (MainThread) [alexapy.alexahttp2] Connecting to https://alexa.eu.gateway.devices.a2z.com/v20160207/directives with {'method': 'GET', 'path': '/v20160207/directives', 'authority': 'alexa.eu.gateway.devices.a2z.com', 'scheme': 'https', 'authorization': 'Bearer Atna|EwICIGk3MAU0L2OWgIac-Tg7NIlzfcUQz4-FlY9sEc2qkUSfvczCJVvQ0RBNzoa1IfUa261pEQ19ut1dKzGgv55vfOZh7McfoAKjOY_23emjJZl6GRUYj_ScziPaAtp9p2hA_t7p1TPBebe1IuT4uqd7pCxrPBd8HNhUnsgQq5dUhtDNIZUTA9h2TGKViyVabf-POD9ePBw3blrcZrFUUeXZGOe7uAgEJeGXykpC94OEtFYcLZcAwBLjdvJyaibHcXLkJrt7_YliKVpm9dsuoSPs-XXFP4dvJBnTcqIbTk5IdX9bb40CmhCWHY8bM-r50Kb-beaycY3o12SzfE-BRcN5r6y8yjOyUEmJW8iWkFnuS0oYrdUxm8Grk7MFHA68YgcrVNg'}
2024-09-03 02:45:32.758 DEBUG (MainThread) [alexapy.alexahttp2] Preparing ping to https://alexa.eu.gateway.devices.a2z.com/ping
2024-09-03 02:45:32.979 DEBUG (MainThread) [alexapy.alexahttp2] Received raw message: Unable to authenticate the request. Please provide a valid authorization token.
2024-09-03 02:45:32.979 DEBUG (MainThread) [alexapy.alexahttp2] HTTP2 login error: Unable to authenticate the request. Please provide a valid authorization token.
2024-09-03 02:45:32.981 DEBUG (MainThread) [alexapy.alexalogin] Attempting to register with amazon.it
2024-09-03 02:45:33.262 DEBUG (MainThread) [alexapy.alexalogin] auth response <ClientResponse(https://api.amazon.it/auth/register) [401 Unauthorized]>
<CIMultiDictProxy('Server': 'Server', 'Date': 'Tue, 03 Sep 2024 00:45:33 GMT', 'Content-Type': 'application/json;charset=UTF-8', 'Content-Length': '253', 'Connection': 'keep-alive', 'x-amz-rid': 'TQNAA3G7YER9RMJQHHKS', 'x-amzn-RequestId': '1ecbd640-0b04-4b54-b535-5ff13516fe0e', 'X-Amz-Date': 'Tue, 03 Sep 2024 00:45:33 GMT', 'WWW-Authenticate': 'Basic realm="api.amazon.it/auth/register"', 'Cache-Control': 'no-cache, no-store, must-revalidate', 'x-amzn-Remapped-WWW-Authenticate': 'Basic realm="api.amazon.it/auth/register"', 'Pragma': 'no-cache', 'Vary': 'Content-Type,Accept-Encoding,User-Agent', 'Strict-Transport-Security': 'max-age=47474747; includeSubDomains; preload')>
 with 
{"requested_extensions": ["device_info", "customer_info"], "cookies": {"website_cookies": [], "domain": ".amazon.it"}, "registration_data": {"domain": "Device", "app_version": "2.2.556530.0", "device_type": "A2IVLV5VM2W81", "device_name": "%FIRST_NAME%'s%DUPE_STRATEGY_1ST%Alexa Media Player", "os_version": "16.6", "device_serial": "051b68318db52310ca72e00409c9b9bc", "device_model": "iPhone", "app_name": "Alexa Media Player", "software_version": "1"}, "auth_data": {"access_token": "Atna|EwICIGk3MAU0L2OWgIac-Tg7NIlzfcUQz4-FlY9sEc2qkUSfvczCJVvQ0RBNzoa1IfUa261pEQ19ut1dKzGgv55vfOZh7McfoAKjOY_23emjJZl6GRUYj_ScziPaAtp9p2hA_t7p1TPBebe1IuT4uqd7pCxrPBd8HNhUnsgQq5dUhtDNIZUTA9h2TGKViyVabf-POD9ePBw3blrcZrFUUeXZGOe7uAgEJeGXykpC94OEtFYcLZcAwBLjdvJyaibHcXLkJrt7_YliKVpm9dsuoSPs-XXFP4dvJBnTcqIbTk5IdX9bb40CmhCWHY8bM-r50Kb-beaycY3o12SzfE-BRcN5r6y8yjOyUEmJW8iWkFnuS0oYrdUxm8Grk7MFHA68YgcrVNg"}, "user_context_map": {"frc": "wGnfIcut4458zo0XMa9IGsFZJRL7epG0MqBfqpTo3XQmcql5ncex/QCVydRLc3/YFfWqqDoX4SD1+VOZzgIp32tQs+suGNzRD7BpWBA/y2mDwC5fbmFO78QT2pMpLzDERvNgWdyUvEGaFpQNmB6k1Db5ttsMSCEem328WWOzm2qhEK8KEhJPY0hlaHWWEYBhaD/kPS/tuUVXRVowkqx970kLTGI66zQ9GvyN9zAynDQBavMn+FXMGzjX65zzpUPF2dDtv9oHoZE5PSDAOXJ0pPOC+pfBZHOx0ska9qcF8jZob1HbKZO8iyV0T+rBVv2uA77fkJHm2tzd2/wS0pHg+AfFOFYS2uxjHuI96uM9ESAcNwCYor4wCe/L5e1MUHSrYeTMfyUa1VlUtFmU4IOKTAuqAGYieWQHsg"}, "requested_token_type": ["bearer", "mac_dms", "website_cookies"]}
2024-09-03 02:45:33.264 DEBUG (MainThread) [alexapy.alexalogin] Attempting to register with amazon.com
2024-09-03 02:45:33.682 DEBUG (MainThread) [alexapy.alexalogin] auth response <ClientResponse(https://api.amazon.com/auth/register) [401 Unauthorized]>
<CIMultiDictProxy('Server': 'Server', 'Date': 'Tue, 03 Sep 2024 00:45:33 GMT', 'Content-Type': 'application/json;charset=UTF-8', 'Content-Length': '254', 'Connection': 'keep-alive', 'x-amz-rid': 'K8R472M2PJF5P9BFKP1V', 'x-amzn-RequestId': '276c4d75-e28b-4c0c-9705-0ca9fa73ecf1', 'X-Amz-Date': 'Tue, 03 Sep 2024 00:45:33 GMT', 'WWW-Authenticate': 'Basic realm="api.amazon.com/auth/register"', 'Cache-Control': 'no-cache, no-store, must-revalidate', 'x-amzn-Remapped-WWW-Authenticate': 'Basic realm="api.amazon.com/auth/register"', 'Pragma': 'no-cache', 'Vary': 'Content-Type,Accept-Encoding,User-Agent', 'Strict-Transport-Security': 'max-age=47474747; includeSubDomains; preload')>
 with 
{"requested_extensions": ["device_info", "customer_info"], "cookies": {"website_cookies": [], "domain": ".amazon.com"}, "registration_data": {"domain": "Device", "app_version": "2.2.556530.0", "device_type": "A2IVLV5VM2W81", "device_name": "%FIRST_NAME%'s%DUPE_STRATEGY_1ST%Alexa Media Player", "os_version": "16.6", "device_serial": "051b68318db52310ca72e00409c9b9bc", "device_model": "iPhone", "app_name": "Alexa Media Player", "software_version": "1"}, "auth_data": {"access_token": "Atna|EwICIGk3MAU0L2OWgIac-Tg7NIlzfcUQz4-FlY9sEc2qkUSfvczCJVvQ0RBNzoa1IfUa261pEQ19ut1dKzGgv55vfOZh7McfoAKjOY_23emjJZl6GRUYj_ScziPaAtp9p2hA_t7p1TPBebe1IuT4uqd7pCxrPBd8HNhUnsgQq5dUhtDNIZUTA9h2TGKViyVabf-POD9ePBw3blrcZrFUUeXZGOe7uAgEJeGXykpC94OEtFYcLZcAwBLjdvJyaibHcXLkJrt7_YliKVpm9dsuoSPs-XXFP4dvJBnTcqIbTk5IdX9bb40CmhCWHY8bM-r50Kb-beaycY3o12SzfE-BRcN5r6y8yjOyUEmJW8iWkFnuS0oYrdUxm8Grk7MFHA68YgcrVNg"}, "user_context_map": {"frc": "wGnfIcut4458zo0XMa9IGsFZJRL7epG0MqBfqpTo3XQmcql5ncex/QCVydRLc3/YFfWqqDoX4SD1+VOZzgIp32tQs+suGNzRD7BpWBA/y2mDwC5fbmFO78QT2pMpLzDERvNgWdyUvEGaFpQNmB6k1Db5ttsMSCEem328WWOzm2qhEK8KEhJPY0hlaHWWEYBhaD/kPS/tuUVXRVowkqx970kLTGI66zQ9GvyN9zAynDQBavMn+FXMGzjX65zzpUPF2dDtv9oHoZE5PSDAOXJ0pPOC+pfBZHOx0ska9qcF8jZob1HbKZO8iyV0T+rBVv2uA77fkJHm2tzd2/wS0pHg+AfFOFYS2uxjHuI96uM9ESAcNwCYor4wCe/L5e1MUHSrYeTMfyUa1VlUtFmU4IOKTAuqAGYieWQHsg"}, "requested_token_type": ["bearer", "mac_dms", "website_cookies"]}
2024-09-03 02:45:33.683 DEBUG (MainThread) [alexapy.alexalogin] Unable to register with ['amazon.it', 'amazon.com']
2024-09-03 02:45:33.870 DEBUG (MainThread) [alexapy.alexalogin] capabilities response <ClientResponse(https://api.amazonalexa.com/v1/devices/@self/capabilities) [403 Forbidden]>
<CIMultiDictProxy('Content-Length': '0', 'Connection': 'keep-alive', 'Server': 'Server', 'Date': 'Tue, 03 Sep 2024 00:45:33 GMT', 'x-amz-rid': 'BDBJQ9Q18CK9X8JQH6CW', 'Vary': 'Content-Type,Accept-Encoding,User-Agent', 'Strict-Transport-Security': 'max-age=47474747; includeSubDomains; preload', 'X-Cache': 'Error from cloudfront', 'Via': '1.1 fd1922963c91836bd3bc6df1671c0612.cloudfront.net (CloudFront)', 'X-Amz-Cf-Pop': 'MXP64-P1', 'X-Amz-Cf-Id': 'V_cVpjG7aVkOvtwHFRJDpP_HiVOLNXua77iHlCID0ridEdQXQIr1DA==')>
 with 
{"legacyFlags": {"SUPPORTS_COMMS": true, "SUPPORTS_ARBITRATION": true, "SCREEN_WIDTH": 1170, "SUPPORTS_SCRUBBING": true, "SPEECH_SYNTH_SUPPORTS_TTS_URLS": false, "SUPPORTS_HOME_AUTOMATION": true, "SUPPORTS_DROPIN_OUTBOUND": true, "FRIENDLY_NAME_TEMPLATE": "VOX", "SUPPORTS_SIP_OUTBOUND_CALLING": true, "VOICE_PROFILE_SWITCHING_DISABLED": true, "SUPPORTS_LYRICS_IN_CARD": false, "SUPPORTS_DATAMART_NAMESPACE": "Vox", "SUPPORTS_VIDEO_CALLING": true, "SUPPORTS_PFM_CHANGED": true, "SUPPORTS_TARGET_PLATFORM": "TABLET", "SUPPORTS_SECURE_LOCKSCREEN": false, "AUDIO_PLAYER_SUPPORTS_TTS_URLS": false, "SUPPORTS_KEYS_IN_HEADER": false, "SUPPORTS_MIXING_BEHAVIOR_FOR_AUDIO_PLAYER": false, "AXON_SUPPORT": true, "SUPPORTS_TTS_SPEECHMARKS": true}, "envelopeVersion": "20160207", "capabilities": [{"version": "0.1", "interface": "CardRenderer", "type": "AlexaInterface"}, {"interface": "Navigation", "type": "AlexaInterface", "version": "1.1"}, {"type": "AlexaInterface", "version": "2.0", "interface": "Alexa.Comms.PhoneCallController"}, {"type": "AlexaInterface", "version": "1.1", "interface": "ExternalMediaPlayer"}, {"type": "AlexaInterface", "interface": "Alerts", "configurations": {"maximumAlerts": {"timers": 2, "overall": 99, "alarms": 2}}, "version": "1.3"}, {"version": "1.0", "interface": "Alexa.Display.Window", "type": "AlexaInterface", "configurations": {"templates": [{"type": "STANDARD", "id": "app_window_template", "configuration": {"sizes": [{"id": "fullscreen", "type": "DISCRETE", "value": {"value": {"height": 1440, "width": 3200}, "unit": "PIXEL"}}], "interactionModes": ["mobile_mode", "auto_mode"]}}]}}, {"type": "AlexaInterface", "interface": "AccessoryKit", "version": "0.1"}, {"type": "AlexaInterface", "interface": "Alexa.AudioSignal.ActiveNoiseControl", "version": "1.0", "configurations": {"ambientSoundProcessingModes": [{"name": "ACTIVE_NOISE_CONTROL"}, {"name": "PASSTHROUGH"}]}}, {"interface": "PlaybackController", "type": "AlexaInterface", "version": "1.0"}, {"version": "1.0", "interface": "Speaker", "type": "AlexaInterface"}, {"version": "1.0", "interface": "SpeechSynthesizer", "type": "AlexaInterface"}, {"version": "1.0", "interface": "AudioActivityTracker", "type": "AlexaInterface"}, {"type": "AlexaInterface", "interface": "Alexa.Camera.LiveViewController", "version": "1.0"}, {"type": "AlexaInterface", "version": "1.0", "interface": "Alexa.Input.Text"}, {"type": "AlexaInterface", "interface": "Alexa.PlaybackStateReporter", "version": "1.0"}, {"version": "1.1", "interface": "Geolocation", "type": "AlexaInterface"}, {"interface": "Alexa.Health.Fitness", "version": "1.0", "type": "AlexaInterface"}, {"interface": "Settings", "type": "AlexaInterface", "version": "1.0"}, {"configurations": {"interactionModes": [{"dialog": "SUPPORTED", "interactionDistance": {"value": 18, "unit": "INCHES"}, "video": "SUPPORTED", "keyboard": "SUPPORTED", "id": "mobile_mode", "uiMode": "MOBILE", "touch": "SUPPORTED"}, {"video": "UNSUPPORTED", "dialog": "SUPPORTED", "interactionDistance": {"value": 36, "unit": "INCHES"}, "uiMode": "AUTO", "touch": "SUPPORTED", "id": "auto_mode", "keyboard": "UNSUPPORTED"}]}, "type": "AlexaInterface", "interface": "Alexa.InteractionMode", "version": "1.0"}, {"type": "AlexaInterface", "configurations": {"catalogs": [{"type": "IOS_APP_STORE", "identifierTypes": ["URI_HTTP_SCHEME", "URI_CUSTOM_SCHEME"]}]}, "version": "0.2", "interface": "Alexa.Launcher"}, {"interface": "System", "version": "1.0", "type": "AlexaInterface"}, {"interface": "Alexa.IOComponents", "type": "AlexaInterface", "version": "1.4"}, {"type": "AlexaInterface", "interface": "Alexa.FavoritesController", "version": "1.0"}, {"version": "1.0", "type": "AlexaInterface", "interface": "Alexa.Mobile.Push"}, {"type": "AlexaInterface", "interface": "InteractionModel", "version": "1.1"}, {"interface": "Alexa.PlaylistController", "type": "AlexaInterface", "version": "1.0"}, {"interface": "SpeechRecognizer", "type": "AlexaInterface", "version": "2.1"}, {"interface": "AudioPlayer", "type": "AlexaInterface", "version": "1.3"}, {"type": "AlexaInterface", "version": "3.1", "interface": "Alexa.RTCSessionController"}, {"interface": "VisualActivityTracker", "version": "1.1", "type": "AlexaInterface"}, {"interface": "Alexa.PlaybackController", "version": "1.0", "type": "AlexaInterface"}, {"type": "AlexaInterface", "interface": "Alexa.SeekController", "version": "1.0"}, {"interface": "Alexa.Comms.MessagingController", "type": "AlexaInterface", "version": "1.0"}]}
{"User-Agent": "AmazonWebView/Amazon Alexa/2.2.556530.0/iOS/16.6/iPhone", "Accept-Language": "en-US", "Accept-Charset": "utf-8", "Connection": "keep-alive", "Content-type": "application/json; charset=UTF-8", "authorization": "Bearer Atna|EwICIGk3MAU0L2OWgIac-Tg7NIlzfcUQz4-FlY9sEc2qkUSfvczCJVvQ0RBNzoa1IfUa261pEQ19ut1dKzGgv55vfOZh7McfoAKjOY_23emjJZl6GRUYj_ScziPaAtp9p2hA_t7p1TPBebe1IuT4uqd7pCxrPBd8HNhUnsgQq5dUhtDNIZUTA9h2TGKViyVabf-POD9ePBw3blrcZrFUUeXZGOe7uAgEJeGXykpC94OEtFYcLZcAwBLjdvJyaibHcXLkJrt7_YliKVpm9dsuoSPs-XXFP4dvJBnTcqIbTk5IdX9bb40CmhCWHY8bM-r50Kb-beaycY3o12SzfE-BRcN5r6y8yjOyUEmJW8iWkFnuS0oYrdUxm8Grk7MFHA68YgcrVNg"}
2024-09-03 02:45:33.871 DEBUG (MainThread) [alexapy.alexalogin] Failed to register capabilities
2024-09-03 02:45:34.190 DEBUG (MainThread) [alexapy.alexalogin] 5 cookies successfully exchanged for refresh token for domain .amazon.it
2024-09-03 02:45:34.191 DEBUG (MainThread) [alexapy.alexalogin] CSRF already exists; no need to discover
2024-09-03 02:45:34.742 DEBUG (MainThread) [alexapy.alexalogin] GET: 
https://alexa.amazon.com/api/bootstrap returned 200:OK with response <CIMultiDictProxy('Content-Type': 'application/json', 'Content-Length': '179', 'Connection': 'keep-alive', 'Server': 'Server', 'Date': 'Tue, 03 Sep 2024 00:45:34 GMT', 'Vary': 'Content-Type,Accept-Encoding,User-Agent', 'x-amz-rid': 'KPXN5DHC89D5GE4B6K0P', 'x-amzn-RequestId': 'KPXN5DHC89D5GE4B6K0P', 'x-amzn-alt-domain': 'https://alexa.amazon.it/logout', 'X-Cache': 'Miss from cloudfront', 'Via': '1.1 946a47118939fc2908c7ce8e46e8d16c.cloudfront.net (CloudFront)', 'X-Amz-Cf-Pop': 'MXP64-P1', 'X-Amz-Cf-Id': '9PUiRYb3sgd4DxOW1Js9xp1M2CoMqoud4qWJ6uA6YT9z76yIwC8Isw==')>
2024-09-03 02:45:35.068 DEBUG (MainThread) [alexapy.alexalogin] GET: 
https://alexa.amazon.it/api/bootstrap returned 200:OK with response <CIMultiDictProxy('Content-Type': 'application/json', 'Content-Length': '179', 'Connection': 'keep-alive', 'Server': 'Server', 'Date': 'Tue, 03 Sep 2024 00:45:35 GMT', 'Strict-Transport-Security': 'max-age=0; includeSubDomains;', 'x-amz-rid': 'ZJ2H45MTRG2MA1X04M3W', 'x-amzn-RequestId': 'ZJ2H45MTRG2MA1X04M3W', 'Vary': 'Content-Type,Accept-Encoding,User-Agent', 'X-Cache': 'Miss from cloudfront', 'Via': '1.1 bbdab68f6dd980a27e635ee335ffbfb0.cloudfront.net (CloudFront)', 'X-Amz-Cf-Pop': 'MXP53-P4', 'X-Amz-Cf-Id': 'HKFczlo2f0htMBn_sW2lM7Z6Ap6wyxg3z5JW63SoflO0rJeuwhmQow==')>
2024-09-03 02:45:35.069 DEBUG (MainThread) [alexapy.alexalogin] Logged in as [email protected] to amazon.it with id: A19N0OQD5SALS3
2024-09-03 02:45:35.579 DEBUG (MainThread) [alexapy.alexalogin] Domain amazon.it matches reported account domain: amazon.it
2024-09-03 02:45:35.587 DEBUG (MainThread) [alexapy.alexahttp2] HTTP2 Connection Closed.
2024-09-03 02:45:42.759 DEBUG (MainThread) [alexapy.alexaapi] s*****0@h********t: Detected access token expiration; refreshing
2024-09-03 02:45:42.834 DEBUG (MainThread) [alexapy.alexalogin] refresh response <ClientResponse(https://api.amazon.it/auth/token) [200 OK]>

AMP then stopped working


2024-09-03 13:47:29.061 WARNING (MainThread) [alexapy.helpers] alexaapi.get_customer_history_records((<alexapy.alexalogin.AlexaLogin object at 0x7f96ae29f0>,), {'max_record_size': 10}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments:
('Unauthorized',)

No interactions made between 2:45 and 13:47...

Just posting this as feedback, maybe someone who reads can understand more.

@matteorossininchi
Copy link

as an update to the above, for now all seems to be working since I posted it.
Http2 session was closed again after around 3 hours and 27 minutes since AMP was restarted. Never opened again so AMP is working without http2 at the moment.

@NdR91
Copy link

NdR91 commented Sep 4, 2024

as an update to the above, for now all seems to be working since I posted it. Http2 session was closed again after around 3 hours and 27 minutes since AMP was restarted. Never opened again so AMP is working without http2 at the moment.

Hey Matteo, thanks for your feedback.

It's not clear to me what did you do to make it working.
You are on amazon.it i guess, so your "method" probably will work for me too...

@matteorossininchi
Copy link

matteorossininchi commented Sep 4, 2024

as an update to the above, for now all seems to be working since I posted it. Http2 session was closed again after around 3 hours and 27 minutes since AMP was restarted. Never opened again so AMP is working without http2 at the moment.

Hey Matteo, thanks for your feedback.

It's not clear to me what did you do to make it working. You are on amazon.it i guess, so your "method" probably will work for me too...

to be honest I didn't change anything from yesterday and I don't think it will work forever. For sure it is working better.
I have the latest AMP version, latest HA version and alexapy 1.29.0 (not in the manifest only, I had to update it through SSH).
Polling disabled as I don't really need it.

But again... I don't think it's fixed, it's just working longer than usual. This is the same setup I used for days and I think it's just luck that it's now working for around 20 hours...

@NdR91
Copy link

NdR91 commented Sep 4, 2024

as an update to the above, for now all seems to be working since I posted it. Http2 session was closed again after around 3 hours and 27 minutes since AMP was restarted. Never opened again so AMP is working without http2 at the moment.

Hey Matteo, thanks for your feedback.
It's not clear to me what did you do to make it working. You are on amazon.it i guess, so your "method" probably will work for me too...

to be honest I didn't change anything from yesterday and I don't think it will work forever. For sure it is working better. I have the latest AMP version, latest HA version and alexapy 1.29.0 (not in the manifest only, I had to update it through SSH). Polling disabled as I don't really need it.

But again... I don't think it's fixed, it's just working longer than usual. This is the same setup I used for days and I think it's just luck that it's now working for around 20 hours...

Thanks Matteo, i just updated the dependencies via ssh and changed the manifest. Will see if this will stay fixed longer...

@figorr
Copy link

figorr commented Sep 4, 2024

I have just updated to the new core 2024.9.0 in order to test if something changed.

I found some new errors I didn't see before in core 2024.8.X

Error 1: This error is new for me. I didn't remember from the 2024.8.X

Registrador: homeassistant.util.loop
Fuente: util/loop.py:136
Ocurrió por primera vez: 18:35:10 (5 ocurrencias)
Última vez registrado: 18:35:37

Detected blocking call to open with args (PosixPath('/config/.storage/alexa_media.<edited>.pickle'),) inside the event loop by custom integration 'alexa_media' at custom_components/alexa_media/__init__.py, line 360: await login.login(cookies=await login.load_cookie()) (offender: /usr/local/lib/python3.12/site-packages/aiohttp/cookiejar.py, line 118: with file_path.open(mode="rb") as f:), please create a bug report at https://github.com/alandtse/alexa_media_player/issues For developers, please see https://developers.home-assistant.io/docs/asyncio_blocking_operations/#open Traceback (most recent call last): File "<frozen runpy>", line 198, in _run_module_as_main File "<frozen runpy>", line 88, in _run_code File "/usr/src/homeassistant/homeassistant/__main__.py", line 223, in <module> sys.exit(main()) File "/usr/src/homeassistant/homeassistant/__main__.py", line 209, in main exit_code = runner.run(runtime_conf) File "/usr/src/homeassistant/homeassistant/runner.py", line 189, in run return loop.run_until_complete(setup_and_run_hass(runtime_config)) File "/usr/local/lib/python3.12/asyncio/base_events.py", line 674, in run_until_complete self.run_forever() File "/usr/local/lib/python3.12/asyncio/base_events.py", line 641, in run_forever self._run_once() File "/usr/local/lib/python3.12/asyncio/base_events.py", line 1990, in _run_once handle._run() File "/usr/local/lib/python3.12/asyncio/events.py", line 88, in _run self._context.run(self._callback, *self._args) File "/usr/src/homeassistant/homeassistant/config_entries.py", line 752, in async_setup_locked await self.async_setup(hass, integration=integration) File "/usr/src/homeassistant/homeassistant/config_entries.py", line 604, in async_setup result = await component.async_setup_entry(hass, self) File "/config/custom_components/alexa_media/__init__.py", line 360, in async_setup_entry await login.login(cookies=await login.load_cookie())

Detected blocking call to open with args (PosixPath('/config/.storage/alexa_media.<edited>.pickle'),) inside the event loop by custom integration 'alexa_media' at custom_components/alexa_media/__init__.py, line 360: await login.login(cookies=await login.load_cookie()) (offender: /usr/local/lib/python3.12/site-packages/aiohttp/cookiejar.py, line 113: with file_path.open(mode="wb") as f:), please create a bug report at https://github.com/alandtse/alexa_media_player/issues For developers, please see https://developers.home-assistant.io/docs/asyncio_blocking_operations/#open Traceback (most recent call last): File "<frozen runpy>", line 198, in _run_module_as_main File "<frozen runpy>", line 88, in _run_code File "/usr/src/homeassistant/homeassistant/__main__.py", line 223, in <module> sys.exit(main()) File "/usr/src/homeassistant/homeassistant/__main__.py", line 209, in main exit_code = runner.run(runtime_conf) File "/usr/src/homeassistant/homeassistant/runner.py", line 189, in run return loop.run_until_complete(setup_and_run_hass(runtime_config)) File "/usr/local/lib/python3.12/asyncio/base_events.py", line 674, in run_until_complete self.run_forever() File "/usr/local/lib/python3.12/asyncio/base_events.py", line 641, in run_forever self._run_once() File "/usr/local/lib/python3.12/asyncio/base_events.py", line 1990, in _run_once handle._run() File "/usr/local/lib/python3.12/asyncio/events.py", line 88, in _run self._context.run(self._callback, *self._args) File "/usr/src/homeassistant/homeassistant/config_entries.py", line 752, in async_setup_locked await self.async_setup(hass, integration=integration) File "/usr/src/homeassistant/homeassistant/config_entries.py", line 604, in async_setup result = await component.async_setup_entry(hass, self) File "/config/custom_components/alexa_media/__init__.py", line 360, in async_setup_entry await login.login(cookies=await login.load_cookie())

Detected blocking call to load_verify_locations with args (<ssl.SSLContext object at 0x7f130f59d7d0>,) inside the event loop by custom integration 'alexa_media' at custom_components/alexa_media/__init__.py, line 875: http2 = HTTP2EchoClient( (offender: /usr/local/lib/python3.12/site-packages/httpx/_config.py, line 147: context.load_verify_locations(cafile=cafile)), please create a bug report at https://github.com/alandtse/alexa_media_player/issues For developers, please see https://developers.home-assistant.io/docs/asyncio_blocking_operations/#load_verify_locations Traceback (most recent call last): File "<frozen runpy>", line 198, in _run_module_as_main File "<frozen runpy>", line 88, in _run_code File "/usr/src/homeassistant/homeassistant/__main__.py", line 223, in <module> sys.exit(main()) File "/usr/src/homeassistant/homeassistant/__main__.py", line 209, in main exit_code = runner.run(runtime_conf) File "/usr/src/homeassistant/homeassistant/runner.py", line 189, in run return loop.run_until_complete(setup_and_run_hass(runtime_config)) File "/usr/local/lib/python3.12/asyncio/base_events.py", line 674, in run_until_complete self.run_forever() File "/usr/local/lib/python3.12/asyncio/base_events.py", line 641, in run_forever self._run_once() File "/usr/local/lib/python3.12/asyncio/base_events.py", line 1990, in _run_once handle._run() File "/usr/local/lib/python3.12/asyncio/events.py", line 88, in _run self._context.run(self._callback, *self._args) File "/usr/src/homeassistant/homeassistant/config_entries.py", line 752, in async_setup_locked await self.async_setup(hass, integration=integration) File "/usr/src/homeassistant/homeassistant/config_entries.py", line 604, in async_setup result = await component.async_setup_entry(hass, self) File "/config/custom_components/alexa_media/__init__.py", line 362, in async_setup_entry await setup_alexa(hass, config_entry, login) File "/config/custom_components/alexa_media/__init__.py", line 1265, in setup_alexa await http2_connect() File "/config/custom_components/alexa_media/__init__.py", line 875, in http2_connect http2 = HTTP2EchoClient(

Error 2: This error occurred under 2024.8.X

Este error se originó a partir de una integración personalizada.

Registrador: alexapy.helpers
Fuente: custom_components/alexa_media/__init__.py:786
integración: Alexa Media Player (documentación, problemas)
Ocurrió por primera vez: 18:46:01 (2 ocurrencias)
Última vez registrado: 18:46:01

alexaapi.get_customer_history_records((<alexapy.alexalogin.AlexaLogin object at 0x7f1309d31310>,), {'max_record_size': 10}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments: ('Unauthorized',)
alexaapi.get_last_device_serial((<alexapy.alexalogin.AlexaLogin object at 0x7f1309d31310>,), {}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments: ('Unauthorized',)

10 minutes after the start of HA 2024.9.0 ... the integration fails.

I am running ...
Amazon alexa media player version: 4.12.11
AlexaPy 1.28.2
Amazon domain: .es
2FA: activate

This time I didn't modify manifest.json file neither the time between scans, I kept the 60s, include devices connected via echo enabled and polling updates.

@figorr
Copy link

figorr commented Sep 4, 2024

I am going to update something I did after the first failed test.

I restored my 2024.7.4 backup I did before the update to core 2024.9.0. And I decided to start again from the begining.

Once the backup was restored ... I downgraded Alexia Media Player from version 4.12.11 to 4.12.7 (I think this was the first release that solved the problem from upgrading from 2024.7.4 to 2024.8.0).

After restarting HA I modified the manifest.json file. I modified the file according to this:

"requirements": ["alexapy>=1.28.2", "packaging>=20.3", "wrapt>=1.14.0"],

Once the file was edited I restarte HA again in order to reload the integration according to this change.

After the restart ... AMP 4.12.7 (with modified manifest.json) seems to work as the 4.12.11 under HA Core 2024.7.4.

So ... I made a new backup and I decided to upgrade HA to 2024.9.0 again.

After the new core has been installed ... I decided to wait ... and after 10 min ... it failed again.

So just I found the integration failed (in my case it is easy to check because the temp sensors from the Echos became unavailable) I deleted the pickle file located at .storage folder and I restarted the integration quickly before this file is created again.

After HA had restarted I think I found an error at logs, I didn't remember. I thought It didn't work the process, but as I was having dinner I decided to wait until I finished in order to restore my backup to 2024.7.4.

But after the dinner I could check the temp sensors did not become unavailable during the last hour. So the integration was still working for more than 10 minutes (without any reload of the integration).

I am going to still monitoring the logs until tomorrow in order to see if it doesn't fail.

Let's see and ... fingers crossed.

@figorr
Copy link

figorr commented Sep 4, 2024

Unfortunately it only worked during 90 min aprox.

Then the previous errors 1 & 2 appeared again.

After that the integration failed and the reload didn’t solved it. (Error unloading entry Alexa for notify). The sensors become available again but tts was not working.

So I restored my 2024.7.4 backup again. :(

@figorr
Copy link

figorr commented Sep 4, 2024

A weird thing ... after restoring the backup to core 2024.7.4 ... with AMP 4.12.11 (and no manifest.json edited) ... after a while I could see a couple errors that made me feel scared.

Error 1: First time 23:01:03 when HA started after the backup restoration. And second one 23:10:28 ... (the usual 10 minutes when AMP pulls for updates).

Registrador: homeassistant.config_entries
Fuente: config_entries.py:801
Ocurrió por primera vez: 23:01:03 (2 ocurrencias)
Último inicio de sesión: 23:10:28

Error unloading entry Alexa for notify
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/config_entries.py", line 801, in async_unload
    result = await component.async_unload_entry(hass, self)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/components/notify/__init__.py", line 135, in async_unload_entry
    return await component.async_unload_entry(entry)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/helpers/entity_component.py", line 202, in async_unload_entry
    raise ValueError("Config entry was never loaded!")
ValueError: Config entry was never loaded!

Error 2: First time 23:01:03 when HA started after the backup restoration. And second one 23:10:28 ... (the usual 10 minutes when AMP pulls for updates).

Este error se originó a partir de una integración personalizada.

Registrador: custom_components.alexa_media
Fuente: custom_components/alexa_media/__init__.py:1355
integración: Alexa Media Player (documentación, problemas)
Ocurrió por primera vez: 23:01:03 (2 ocurrencias)
Último inicio de sesión: 23:10:29

Could not remove cookiefile: /config/.storage/alexa_media.<edited>.pickle. Please manually delete the file.

That errors are the errors I saw when the integration fails under 2024.8.X adn 2024.9.0. But this was the first time I saw these errors under 2024.7.4. Every time I restored the backup ... the integration worked without error ... so I was scared and I thought I completely broke the integration, even under 2024.7.4.

So, I deleted the pickle file and reload the integration ... and now looks like it is working again under 2024.7.4.

@jleinenbach
Copy link

jleinenbach commented Sep 4, 2024

ValueError: Config entry was never loaded!

This is not an issue according to @danielbrunt57 - This should be a warning, not an error.

Could not remove cookiefile: /config/.storage/alexa_media..pickle. Please manually delete the file.

This was fixed with the latest alexapy 1.29.0 version.

@jleinenbach
Copy link

Error 1: This error is new for me. I didn't remember from the 2024.8.X

Detected blocking call to open with args

This is not an AMP issue. These messages were introduced by HA 2024.8 to speed up the HA boot/ initialization process by forcing the programmers to optimize the code.

@Frucoboti
Copy link

4.11.2 versions works as expected, with latest HA .9 version.

Try to downgrade until the issue is corrected.

@metalmarco
Copy link

4.11.2 versions works as expected, with latest HA .9 version.

Try to downgrade until the issue is corrected.

Does version 4.11.2 fix the issue?

@Frucoboti
Copy link

4.11.2 versions works as expected, with latest HA .9 version.
Try to downgrade until the issue is corrected.

Does version 4.11.2 fix the issue?

It certainly doesn't correct. It's just that it keeps working, it hasn't stopped working.

@metalmarco
Copy link

Sorry @Frucoboti but I'm having trouble understanding your last 2 comments, maybe it's my fault.

In the first post you say:

4.11.2 versions works as expected, with latest HA .9 version.

Try to downgrade until the issue is corrected.

So you are saying that it works, but that you also should downgrade. Why would I downgrade if it works?

In your second post you wrote

It certainly doesn't correct. It's just that it keeps working, it hasn't stopped working.

Also here you're saying that it doesn't correct the issue, but also that "it keeps working". So I don't understand if it works or not...

@Frucoboti
Copy link

Don't worry, I mean:

4.11.2 always has been working, with all HA versions.

You can downgrade from any newer version to this, going to HACS, selecting 4.11.2 version.

image

Better now? :-)

@metalmarco
Copy link

Thanks it's clear now.
Everybody is talking to downgrade HA to 2020.7, so I thought you were suggesting to downgrade HA, not AMP.

So, to recap, you're saying the combination HA 2020.9 + AMP 4.11.2 works.

@figorr
Copy link

figorr commented Sep 5, 2024

Thank you @Frucoboti for your feedback.

Just some more questions about your setup in order to discard if something else is breaking the integration.

@matteorossininchi
Copy link

as an update to the above, for now all seems to be working since I posted it. Http2 session was closed again after around 3 hours and 27 minutes since AMP was restarted. Never opened again so AMP is working without http2 at the moment.

Hey Matteo, thanks for your feedback.
It's not clear to me what did you do to make it working. You are on amazon.it i guess, so your "method" probably will work for me too...

to be honest I didn't change anything from yesterday and I don't think it will work forever. For sure it is working better. I have the latest AMP version, latest HA version and alexapy 1.29.0 (not in the manifest only, I had to update it through SSH). Polling disabled as I don't really need it.
But again... I don't think it's fixed, it's just working longer than usual. This is the same setup I used for days and I think it's just luck that it's now working for around 20 hours...

Thanks Matteo, i just updated the dependencies via ssh and changed the manifest. Will see if this will stay fixed longer...

Mine has been working fine for 48 hours.. I used some TTS and update_last_called is still working at the moment.
Not sure why or how. Polling still disabled as I don't really need it

@Frucoboti
Copy link

Thanks it's clear now. Everybody is talking to downgrade HA to 2020.7, so I thought you were suggesting to downgrade HA, not AMP.

So, to recap, you're saying the combination HA 2020.9 + AMP 4.11.2 works.

Thats is!

image
image

Thank you @Frucoboti for your feedback.

Just some more questions about your setup in order to discard if something else is breaking the integration.

Sorry, your github link don't works for me. But I understand your question.
I don't use 'last called device' function, because never it worked fine for me.
I use SMS from Amazon authentication. So the password configured in AMP is a Application password created as install docs says.

@samuelecarpene
Copy link

samuelecarpene commented Sep 5, 2024

@Frucoboti for me is not working.
I'm using:

  • HA CORE 2024.9.0
  • AMP 4.11.2
  • Authentication with otp app (set as default in amazon.it)
  • Home assistant reachable from internal ip on port 8123 (in http) and from external on another port (with caddy as proxy and ssl management in https)

Here my log
image

@danielbrunt57
Copy link
Collaborator Author

Could not remove cookiefile: /config/.storage/alexa_media..pickle. Please manually delete the file.

This was fixed with the latest alexapy 1.29.0 version.

4.12.12 will now remove the .pickle file, even on alexapy 1.28.2...

@CKGrafico
Copy link

Not sure if related but after installation from HACS I've this popup
image

That opens an amazon login page, I write the user, the password and asks again the user, the password, etc..

Console:
image

@JackTalisker
Copy link

Today I decided to disable polling since AMP lasts maximum 10 minutes after startup.
Now AMP has been running for 7 hours.
I will keep you updated

@DOK87
Copy link

DOK87 commented Sep 12, 2024

Has there been any update regarding the problem?
I tried to downgrade AMP to version 4.10.3 but in any case the integration only remains connected for a short time. Then it gives an error.

Registratore: homeassistant.config_entries
Fonte: config_entries.py:604
Prima occorrenza: 08:14:41 (1 occorrenze)
Ultima registrazione: 08:14:41

Error setting up entry *******************@gmail.com - amazon.it for alexa_media
Traceback (most recent call last):
File "/usr/src/homeassistant/homeassistant/config_entries.py", line 604, in async_setup
result = await component.async_setup_entry(hass, self)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/config/custom_components/alexa_media/init.py", line 335, in async_setup_entry
await login.login(cookies=await login.load_cookie())
File "/usr/local/lib/python3.12/site-packages/alexapy/helpers.py", line 137, in wrapper
return await func(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.12/site-packages/alexapy/alexalogin.py", line 687, in login
post_resp = await self._session.post(
^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.12/site-packages/aiohttp/client.py", line 586, in _request
raise err_exc_cls(url)
aiohttp.client_exceptions.InvalidUrlClientError: /errors/validateCaptcha

@Gajotres
Copy link

You will find at least 2-3 semi-working solutions in the last 3-4 weeks of this issue, but to my knowledge and experience none of them are stable enough. We can join with these aproaches, but sooner or later we will be asked to re-authenticate (which is a burden if we need to do these semi-working solutions over and over again).

@DOK87
Copy link

DOK87 commented Sep 12, 2024

Luckily I don't use AMP that heavily. I can temporarily do without it, using other devices. But I need it to go back to a stable version so I can use it in the automations I have at the moment. Otherwise it is systematic that when automation is needed AMP is in logoff.

I hope that the programmers will be able to find a solution in the next updates, and that the integration will work correctly again like it did a few months ago.

@fsecond3bis
Copy link

Hi, same for me.
HA core 2024.9.1 (tried 2024.8.2 as well)
AMP any version
amazon domain: .it
2FA: yes

error log:
2024-09-13 10:08:00.780 WARNING (MainThread) [alexapy.helpers] alexaapi.get_customer_history_records((<alexapy.alexalogin.AlexaLogin object at 0x7f9788e152b0>,), {'max_record_size': 10}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments: ('Unauthorized',) 2024-09-13 10:08:00.781 WARNING (MainThread) [alexapy.helpers] alexaapi.get_last_device_serial((<alexapy.alexalogin.AlexaLogin object at 0x7f9788e152b0>,), {}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments: ('Unauthorized',) 2024-09-13 10:18:06.822 WARNING (MainThread) [alexapy.helpers] alexaapi.set_light_state((<alexapy.alexalogin.AlexaLogin object at 0x7f9788e152b0>, '0266e9a7-8951-466e-a733-40607568fee7', True), {'brightness': None, 'color_temperature_name': None, 'color_name': None}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments: ('Login error detected; not contacting API',) 2024-09-13 10:18:06.822 ERROR (MainThread) [homeassistant.components.websocket_api.http.connection] [140288324860752] Unexpected exception Traceback (most recent call last): File "/usr/src/homeassistant/homeassistant/components/websocket_api/commands.py", line 245, in handle_call_service response = await hass.services.async_call( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/src/homeassistant/homeassistant/core.py", line 2761, in async_call response_data = await coro ^^^^^^^^^^ File "/usr/src/homeassistant/homeassistant/core.py", line 2804, in _execute_service return await target(service_call) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/src/homeassistant/homeassistant/helpers/service.py", line 996, in entity_service_call single_response = await _handle_entity_call( ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/src/homeassistant/homeassistant/helpers/service.py", line 1068, in _handle_entity_call result = await task ^^^^^^^^^^ File "/usr/src/homeassistant/homeassistant/components/light/__init__.py", line 626, in async_handle_light_on_service await light.async_turn_on(**filter_turn_on_params(light, params)) File "/config/custom_components/alexa_media/light.py", line 294, in async_turn_on await self._set_state(True, brightness, kelvin, hs_color) File "/config/custom_components/alexa_media/light.py", line 245, in _set_state response = await AlexaAPI.set_light_state( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/alexapy/helpers.py", line 137, in wrapper return await func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/alexapy/alexaapi.py", line 1644, in set_light_state response = await AlexaAPI._static_request( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/backoff/_async.py", line 151, in retry ret = await target(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/alexapy/alexaapi.py", line 319, in _static_request raise AlexapyLoginError("Login error detected; not contacting API") alexapy.errors.AlexapyLoginError: Login error detected; not contacting API 2024-09-13 10:18:19.816 DEBUG (MainThread) [custom_components.alexa_media.alexa_entity] Coordinator data for 0********************************ee7 is too old to be returned. 2024-09-13 10:18:19.817 DEBUG (MainThread) [alexapy.alexaapi] d*******************i@g*******m: Login error detected; ignoring put request to /api/phoenix/state with {'controlRequests': [{'entityId': '0266e9a7-8951-466e-a733-40607568fee7', 'entityType': 'ENTITY', 'parameters': {'action': 'turnOn'}}]} None 2024-09-13 10:18:19.817 WARNING (MainThread) [alexapy.helpers] alexaapi.set_light_state((<alexapy.alexalogin.AlexaLogin object at 0x7f9788e152b0>, '0266e9a7-8951-466e-a733-40607568fee7', True), {'brightness': None, 'color_temperature_name': None, 'color_name': None}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments: ('Login error detected; not contacting API',) 2024-09-13 10:18:19.817 ERROR (MainThread) [homeassistant.components.websocket_api.http.connection] [140288324860752] Unexpected exception Traceback (most recent call last): File "/usr/src/homeassistant/homeassistant/components/websocket_api/commands.py", line 245, in handle_call_service response = await hass.services.async_call( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/src/homeassistant/homeassistant/core.py", line 2761, in async_call response_data = await coro ^^^^^^^^^^ File "/usr/src/homeassistant/homeassistant/core.py", line 2804, in _execute_service return await target(service_call) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/src/homeassistant/homeassistant/helpers/service.py", line 996, in entity_service_call single_response = await _handle_entity_call( ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/src/homeassistant/homeassistant/helpers/service.py", line 1068, in _handle_entity_call result = await task ^^^^^^^^^^ File "/usr/src/homeassistant/homeassistant/components/light/__init__.py", line 626, in async_handle_light_on_service await light.async_turn_on(**filter_turn_on_params(light, params)) File "/config/custom_components/alexa_media/light.py", line 294, in async_turn_on await self._set_state(True, brightness, kelvin, hs_color) File "/config/custom_components/alexa_media/light.py", line 245, in _set_state response = await AlexaAPI.set_light_state( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/alexapy/helpers.py", line 137, in wrapper return await func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/alexapy/alexaapi.py", line 1644, in set_light_state response = await AlexaAPI._static_request( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/backoff/_async.py", line 151, in retry ret = await target(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/alexapy/alexaapi.py", line 319, in _static_request raise AlexapyLoginError("Login error detected; not contacting API")

@francescoknight
Copy link

I had this problem from about 3 weeks i have fixed just re-downloading alexa media player from hacs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests