kia_uvo: [Kia/Hyundai EU] Integration stops working after some time (invalid device id)

Region and Brand of car

Europe (UK), Kia (e-Niro)

Version of the integration

2.10.4

Describe the bug I know there have been issues the last few days and a flurry up updates to fix it, but I’m running the latest release and still having issues.

Last night my charging automation didn’t work; the start/stop charge service calls resulted in messages such as:

Server returned: 'Invalid request body - Invalid deviceId. ’

This morning I enabled debug logging in the integration and restarted Home Assistant, which resulted in it taking a very long time but I’m not sure if that’s expected. The startup log complains about:

“Force update failed, falling back to cached: Request timeout. - Request timeout.”

However it does manage to list the vehicles and obtain the cached data OK.

Debug logs if an error occurred

When calling the stop_charge service:

2023-07-04 08:53:41.986 DEBUG (SyncWorker_22) [hyundai_kia_connect_api.KiaUvoApiEU] hyundai_kia_connect_api - Stop Charge Action Request {'action': 'stop', 'deviceId': '1591fb40-0738-4daf-8b68-b5a5bbbd9785'}
2023-07-04 08:53:41.986 DEBUG (SyncWorker_22) [hyundai_kia_connect_api.KiaUvoApiEU] hyundai_kia_connect_api - get_stamp 2023-07-04 05:02:13.150000+00:00 120000 85 998 85.74030704166667
2023-07-04 08:53:42.133 DEBUG (SyncWorker_22) [hyundai_kia_connect_api.KiaUvoApiEU] hyundai_kia_connect_api - Stop Charge Action Response: {'retCode': 'F', 'resCode': '4002', 'resMsg': 'Invalid request body - Invalid deviceId. ', 'msgId': '77ce6410-6146-4b27-8bbd-9d9dafbb9952'}
2023-07-04 08:53:42.134 ERROR (MainThread) [homeassistant.helpers.script.websocket_api_script] websocket_api script: Error executing script. Unexpected error for call_service at pos 1: Server returned: 'Invalid request body - Invalid deviceId. '
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 452, in _async_step
    await getattr(self, handler)()
  File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 685, in _async_call_service_step
    await service_task
  File "/usr/src/homeassistant/homeassistant/core.py", line 1910, in async_call
    task.result()
  File "/usr/src/homeassistant/homeassistant/core.py", line 1950, in _execute_service
    await cast(Callable[[ServiceCall], Awaitable[None]], handler.job.target)(
  File "/config/custom_components/kia_uvo/services.py", line 105, in async_handle_stop_charge
    await coordinator.async_stop_charge(vehicle_id)
  File "/config/custom_components/kia_uvo/coordinator.py", line 219, in async_stop_charge
    await self.hass.async_add_executor_job(
  File "/usr/local/lib/python3.11/concurrent/futures/thread.py", line 58, in run
    result = self.fn(*self.args, **self.kwargs)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/config/deps/lib/python3.11/site-packages/hyundai_kia_connect_api/VehicleManager.py", line 151, in stop_charge
    return self.api.stop_charge(self.token, self.get_vehicle(vehicle_id))
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/config/deps/lib/python3.11/site-packages/hyundai_kia_connect_api/KiaUvoApiEU.py", line 854, in stop_charge
    _check_response_for_errors(response)
  File "/config/deps/lib/python3.11/site-packages/hyundai_kia_connect_api/KiaUvoApiEU.py", line 111, in _check_response_for_errors
    raise APIError(f"Server returned: '{response['resMsg']}'")
hyundai_kia_connect_api.exceptions.APIError: Server returned: 'Invalid request body - Invalid deviceId. '
2023-07-04 08:53:42.139 ERROR (MainThread) [homeassistant.components.websocket_api.http.connection] [140567518132112] Error handling message: Unknown error (unknown_error) Chris Boot from 2001:67c:2e80:60:450d:474a:2a87:cf17 (Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36)
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/components/websocket_api/decorators.py", line 26, in _handle_async_response
    await func(hass, connection, msg)
  File "/usr/src/homeassistant/homeassistant/components/websocket_api/commands.py", line 678, in handle_execute_script
    await script_obj.async_run(msg.get("variables"), context=context)
  File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 1533, in async_run
    await asyncio.shield(run.async_run())
  File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 410, in async_run
    await self._async_step(log_exceptions=False)
  File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 454, in _async_step
    self._handle_exception(
  File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 477, in _handle_exception
    raise exception
  File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 452, in _async_step
    await getattr(self, handler)()
  File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 685, in _async_call_service_step
    await service_task
  File "/usr/src/homeassistant/homeassistant/core.py", line 1910, in async_call
    task.result()
  File "/usr/src/homeassistant/homeassistant/core.py", line 1950, in _execute_service
    await cast(Callable[[ServiceCall], Awaitable[None]], handler.job.target)(
  File "/config/custom_components/kia_uvo/services.py", line 105, in async_handle_stop_charge
    await coordinator.async_stop_charge(vehicle_id)
  File "/config/custom_components/kia_uvo/coordinator.py", line 219, in async_stop_charge
    await self.hass.async_add_executor_job(
  File "/usr/local/lib/python3.11/concurrent/futures/thread.py", line 58, in run
    result = self.fn(*self.args, **self.kwargs)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/config/deps/lib/python3.11/site-packages/hyundai_kia_connect_api/VehicleManager.py", line 151, in stop_charge
    return self.api.stop_charge(self.token, self.get_vehicle(vehicle_id))
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/config/deps/lib/python3.11/site-packages/hyundai_kia_connect_api/KiaUvoApiEU.py", line 854, in stop_charge
    _check_response_for_errors(response)
  File "/config/deps/lib/python3.11/site-packages/hyundai_kia_connect_api/KiaUvoApiEU.py", line 111, in _check_response_for_errors
    raise APIError(f"Server returned: '{response['resMsg']}'")
hyundai_kia_connect_api.exceptions.APIError: Server returned: 'Invalid request body - Invalid deviceId. '

To Reproduce Call the kia_uvo.stop_charge (with a valid device_id from the web ui popup).

Expected behavior Car should stop charging etc…

Screenshots n/a

Additional context

About this issue

  • Original URL
  • State: closed
  • Created a year ago
  • Reactions: 4
  • Comments: 58 (8 by maintainers)

Commits related to this issue

Most upvoted comments

Set this up for my mate calling a service like start climate works once then stops working with device id unknown.

Removing the integration adding again allows one more go then after first service stops working again

I have also updated to 2.10.4 and then Integration works for some hours, and then i need to Reload integration… If i keep reloading my integration, it keeps working…

I am currently working on a rust version of the hyundai / kia connect library and also noticed this issue and just wanted to share my solution to it. From my understanding every vehicle action like locking / unlocking / setting charging etc. invalidates the device id, so that following requests fail. I solved this in my api by querying a new device id after each action, which takes less time (200ms) than redoing a complete login (1s). However i still feel like there must be a better way to do this, but this was the only one that i found after trying for a long time, hope this helps.

For me it works until i ask the integration to do something. Then it does it but must be reloaded afterwards.

Confirmed working here in UK/Kia EV6.

Thanks to all who worked on this!

YES it works! Thank you so much phantomsforever! 🤩🙏

Here is the Yaml version of the script: Screenshot 2023-10-28 130203

For some reason your approach did not work for me, so I actually wrote a script and the tap action only calls the script. The device ID is always the same - basically your KIA or Hyunday

Screenshot 2023-10-28 130039

I have looked through to the logs now to try and figure out what’s happening.

The first request (even before login) the integration sends during startup is “get device id” to a /notifications/register endpoint. I assume the deviceId parameter fetched here denotes the notification-receiving device. This parameter is then sent as part of the request for commands like e.g. start/stop charge - presumably those which trigger a notification. This parameter is then invalidated on Hyundai’s servers for some reason, making subsequent requests fail as they send the now invalidated deviceId parameter, hence leading to the error response we are observing. Reloading the integration fixes this, as on (re-)start it will fetch a fresh deviceId.

I probably didn’t get it entirely right and it’ll be obvious to many here, still wanted to write it down to help clarify to other users like myself.

I guess the naive fix would be to fetch a new deviceId once the current one has been “used” but that’s probably just a hack. Happy for some feedback and discussion to get this sorted.

You’re probably right, as the call to set charge limits seems to succeed after reloading the integration, at least once 😃.

I have looked through to the logs now to try and figure out what’s happening.

The first request (even before login) the integration sends during startup is “get device id” to a /notifications/register endpoint. I assume the deviceId parameter fetched here denotes the notification-receiving device. This parameter is then sent as part of the request for commands like e.g. start/stop charge - presumably those which trigger a notification. This parameter is then invalidated on Hyundai’s servers for some reason, making subsequent requests fail as they send the now invalidated deviceId parameter, hence leading to the error response we are observing. Reloading the integration fixes this, as on (re-)start it will fetch a fresh deviceId.

I probably didn’t get it entirely right and it’ll be obvious to many here, still wanted to write it down to help clarify to other users like myself.

I guess the naive fix would be to fetch a new deviceId once the current one has been “used” but that’s probably just a hack. Happy for some feedback and discussion to get this sorted.

i’m having the same issue, except that i’m unable to get it working by reloading the integration.

i own a Hyundai Kona EV

here are the logs:

Unexpected error fetching kia_uvo data: 'redirectUrl'
Traceback (most recent call last):
  File "/usr/local/lib/python3.11/site-packages/hyundai_kia_connect_api/KiaUvoApiEU.py", line 213, in login
    authorization_code = self._get_authorization_code_with_redirect_url(
                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/hyundai_kia_connect_api/KiaUvoApiEU.py", line 1154, in _get_authorization_code_with_redirect_url
    parsed_url = urlparse(response["redirectUrl"])
                          ~~~~~~~~^^^^^^^^^^^^^^^
KeyError: 'redirectUrl'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/update_coordinator.py", line 283, in _async_refresh
    self.data = await self._async_update_data()
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/config/custom_components/kia_uvo/coordinator.py", line 107, in _async_update_data
    await self.async_check_and_refresh_token()
  File "/config/custom_components/kia_uvo/coordinator.py", line 166, in async_check_and_refresh_token
    await self.hass.async_add_executor_job(
  File "/usr/local/lib/python3.11/concurrent/futures/thread.py", line 58, in run
    result = self.fn(*self.args, **self.kwargs)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/hyundai_kia_connect_api/VehicleManager.py", line 120, in check_and_refresh_token
    self.initialize()
  File "/usr/local/lib/python3.11/site-packages/hyundai_kia_connect_api/VehicleManager.py", line 64, in initialize
    self.token: Token = self.api.login(self.username, self.password)
                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/hyundai_kia_connect_api/KiaUvoApiEU.py", line 218, in login
    authorization_code = self._get_authorization_code_with_form(
                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/hyundai_kia_connect_api/KiaUvoApiEU.py", line 1252, in _get_authorization_code_with_form
    parsed_url = urlparse(response["redirectUrl"])
                          ~~~~~~~~^^^^^^^^^^^^^^^
KeyError: 'redirectUrl'

but i also noticed, that i’m now unable to log into the BlueLink App on my phone 🫣 do you think it has something to do with the integration?

Thanks all, we were able to figure out the problem (not the solution) here.

While connecting to Hyundai/Kia EU servers, we have to supply a unique id to receive push notifications about commands sent to cars. Until last week, we were using a fixed id as we were not actually connecting with the push notifications servers, this week, we started to generate random numbers (following the expected pattern) but still not connected to respective servers.

Apparently, our registration mechanism with random id is invalidated after you receive your first push notification from your car. Next time, when integration tries to do an action, it generates an invalid device id error.

Indeed, same as @RuneNyhuus - this stops working after a while. Reloading the integration brings it back to life for a finite amount of time before it starts failing again with the “Invalid request body - Invalid deviceId.” error.

I updated to 2.10.4 on 3rd July evening and everything worked. I also had correct numbers in EV remaining distance and fuel remaining distance sensors, which I never had correct (KIA sorento phev). However, today on 4th I forced update, locked car remotely and a couple of minutes later I got the same error as before:

Logger: homeassistant.components.websocket_api.http.connection Source: custom_components/kia_uvo/coordinator.py:159 Integration: Home Assistant WebSocket API (documentation, issues) First occurred: 11:41:00 (3 occurrences) Last logged: 12:33:06

[140426700196496] Server returned: 'Invalid request body - Invalid deviceId. ’ [140427499349968] Server returned: 'Invalid request body - Invalid deviceId. ’ [140426702490192] Server returned: 'Invalid request body - Invalid deviceId. ’ Traceback (most recent call last): File “/usr/src/homeassistant/homeassistant/components/websocket_api/commands.py”, line 205, in handle_call_service await hass.services.async_call( File “/usr/src/homeassistant/homeassistant/core.py”, line 1910, in async_call task.result() File “/usr/src/homeassistant/homeassistant/core.py”, line 1950, in _execute_service await cast(Callable[[ServiceCall], Awaitable[None]], handler.job.target)( File “/config/custom_components/kia_uvo/services.py”, line 49, in async_handle_force_update await coordinator.async_force_update_all() File “/config/custom_components/kia_uvo/coordinator.py”, line 159, in async_force_update_all await self.hass.async_add_executor_job( File “/usr/local/lib/python3.11/concurrent/futures/thread.py”, line 58, in run result = self.fn(*self.args, **self.kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File “/usr/local/lib/python3.11/site-packages/hyundai_kia_connect_api/VehicleManager.py”, line 109, in force_refresh_all_vehicles_states self.force_refresh_vehicle_state(vehicle_id) File “/usr/local/lib/python3.11/site-packages/hyundai_kia_connect_api/VehicleManager.py”, line 114, in force_refresh_vehicle_state self.api.force_refresh_vehicle_state(self.token, vehicle) File “/usr/local/lib/python3.11/site-packages/hyundai_kia_connect_api/KiaUvoApiEU.py”, line 322, in force_refresh_vehicle_state state = self._get_forced_vehicle_state(token, vehicle) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File “/usr/local/lib/python3.11/site-packages/hyundai_kia_connect_api/KiaUvoApiEU.py”, line 739, in _get_forced_vehicle_state _check_response_for_errors(response) File “/usr/local/lib/python3.11/site-packages/hyundai_kia_connect_api/KiaUvoApiEU.py”, line 111, in _check_response_for_errors raise APIError(f"Server returned: ‘{response[‘resMsg’]}’") hyundai_kia_connect_api.exceptions.APIError: Server returned: 'Invalid request body - Invalid deviceId. ’

I also still have non-working integration. Seems previous post has been closed prematurely.