Giter Site home page Giter Site logo

hyundai-kia-connect / hyundai_kia_connect_api Goto Github PK

View Code? Open in Web Editor NEW
113.0 21.0 67.0 971 KB

This is a Kia UVO and Hyundai Bluelink written in python. It is primary consumed by home assistant. If you are looking for a home assistant Kia / Hyundai implementation please look here: https://github.com/Hyundai-Kia-Connect/kia_uvo. Much of this base code came from reading bluelinky and contributions to the kia_uvo home assistant project.

License: MIT License

Makefile 0.79% Python 99.21%
bluelink car homeassistant homeassistant-integration hyundai kia uvo

hyundai_kia_connect_api's Introduction

Code Maintainers Wanted

I no longer have a Kia or Hyundai so don't maintain this like I used to. Others who are interested in jumping in are welcome to join the project! Even just pull requests are appreciated!

Introduction

This is a Kia UVO, Hyundai Bluelink, Genesis Connect(Canada Only) written in python. It is primary consumed by home assistant. If you are looking for a home assistant Kia / Hyundai implementation please look here: https://github.com/fuatakgun/kia_uvo. Much of this base code came from reading bluelinky and contributions to the kia_uvo home assistant project.

Usage

This package is designed to simplify the complexity of using multiple regions. It attempts to standardize the usage regardless of what brand or region the car is in. That isn't always possible though, in particular some features differ from one to the next.

Python 3.9 or newer is required to use this package. Vehicle manager is the key class that is called to manage the vehicle lists. One vehicle manager should be used per login. Key data points required to instantiate vehicle manager are:

region: int
brand: int,
username: str
password: str
pin: str (required for CA, and potentially USA, otherwise pass a blank string)

Key values for the int exist in the constant(https://github.com/fuatakgun/hyundai_kia_connect_api/blob/master/hyundai_kia_connect_api/const.py) file as:

REGIONS = {1: REGION_EUROPE, 2: REGION_CANADA, 3: REGION_USA, 4: REGION_CHINA, 5: REGION_AUSTRALIA}
BRANDS = {1: BRAND_KIA, 2: BRAND_HYUNDAI, 3: BRAND_GENESIS}

Once this is done you can now make the following calls against the vehicle manager:

#Checks the token is still valid and updates it if not.  Should be called before anything else if the code has been running for any length of time.
check_and_refresh_token(self)

Ideal refresh command. Checks if the car has been updated since the time in seconds provided.  If so does a cached update. If not force calls the car.
check_and_force_update_vehicles(self, force_refresh_interval) # Interval in seconds - consider API Rate Limits https://github.com/Hacksore/bluelinky/wiki/API-Rate-Limits

Used to return a specific vehicle object:
get_vehicle(self, vehicle_id)

#Updates all cars with what is cached in the cloud:
update_all_vehicles_with_cached_state(self)

Updates a specific car with cached state:
update_vehicle_with_cached_state(self, vehicle_id)

Force refreshes all cars:
force_refresh_all_vehicles_states(self)

Force refreshes a single car:
force_refresh_vehicles_states(self, vehicle_id)

An example call would be:

from hyundai_kia_connect_api import *
vm = VehicleManager(region=2, brand=1, username="[email protected]", password="password", pin="1234")
vm.check_and_refresh_token()
vm.update_all_vehicles_with_cached_state()
print(vm.vehicles)

If geolocation is required you can also allow this by running:

vm = VehicleManager(region=2, brand=1, username="[email protected]", password="password", pin="1234", geocode_api_enable=True, geocode_api_use_email=True)

This will populate the address of the vehicle in the vehicle instance.

The Bluelink App is reset to English for users who have set another language in the Bluelink App in Europe when using hyundai_kia_connect_api. To avoid this, you can pass the optional parameter language (default is "en") to the constructor of VehicleManager, e.g. for Dutch:

vm = VehicleManager(region=2, brand=1, username="[email protected]", password="password", pin="1234", language="nl")

Note: this is only implemented for Europe currently.

For a list of language codes, see here: https://www.science.co.il/language/Codes.php. Currently in Europe the Bluelink App shows the following languages:

- "en" English
- "de" German
- "fr" French
- "it" Italian
- "es" Spanish
- "sv" Swedish
- "nl" Dutch
- "no" Norwegian
- "cs" Czech
- "sk" Slovak
- "hu" Hungarian
- "da" Danish
- "pl" Polish
- "fi" Finnish
- "pt" Portuguese

In Europe also trip info can be retrieved. For a month you can ask the days with trips. And you can ask for a specific day for all the trips of that specific day.:: - First call vm.update_month_trip_info(vehicle.id, yyymm) before getting vehicle.month_trip_info for that month - First call vm.update_day_trip_info(vehicle.id, day.yyyymmdd) before getting vehicle.day_trip_info for that day

Example of getting trip info of the current month and day (vm is VehicleManager instance):

now = datetime.now()
yyymm = now.strftime("%Y%m")
yyyymmdd = now.strftime("%Y%m%d")
vm.update_month_trip_info(vehicle.id, yyymm)
if vehicle.month_trip_info is not None:
    for day in vehicle.month_trip_info.day_list:  # ordered on day
        if yyyymmdd == day.yyyymmdd:  # in example only interested in current day
            vm.update_day_trip_info(vehicle.id, day.yyyymmdd)
            if vehicle.day_trip_info is not None:
                for trip in reversed(vehicle.day_trip_info.trip_list):  # show oldest first
                    print(f"{day.yyyymmdd},{trip.hhmmss},{trip.drive_time},{trip.idle_time},{trip.distance},{trip.avg_speed},{trip.max_speed}")

hyundai_kia_connect_api's People

Contributors

abdullah818 avatar actions-user avatar asychow avatar bitnimble avatar bubo08 avatar cdnninja avatar chasebolt avatar dependabot[bot] avatar fhempy avatar fuatakgun avatar jrnk avatar jwefers avatar jwillemsen avatar lars-comtide avatar npike avatar nprez83 avatar pkarimov avatar pre-commit-ci[bot] avatar renatkh avatar rjantoine avatar robhammond avatar stephenjamieson avatar toraidl avatar torbjornaxelsson avatar triple-s avatar whinis avatar willemd61 avatar zphaze avatar zuinigerijder avatar zulufoxtrot avatar

Stargazers

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

Watchers

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

hyundai_kia_connect_api's Issues

Discussion: Using unit based functions

Current usage:

 vehicle.fuel_driving_range = 
(get_child_value(state,"vehicleStatus.dte.value",),DISTANCE_UNITS[get_child_value(state, "vehicleStatus.dte.unit")])


vehicle.ev_target_range_charge_DC = (
            get_child_value(
                state,
                "vehicleStatus.evStatus.reservChargeInfos.targetSOClist.0.dte.rangeByFuel.totalAvailableRange.value",
            ),
            DISTANCE_UNITS[
                get_child_value(
                    state,
                    "vehicleStatus.evStatus.reservChargeInfos.targetSOClist.0.dte.rangeByFuel.totalAvailableRange.unit",
                )
            ],
        )

New proposal:

@dataclass
class UnitMapper:
  value_field: str
  unit_field: str = None
  def __post_init__(self):
        if self.unit_field is None:
          splitted = self.value_field.rsplit(".", 1)
          splitted[1] = "unit"
          self.unit_field = ".".join(b)

class UnitBasedFieldDefinition(Enum):
  fuel_driving_range= UnitMapper("vehicleStatus.dte.value")
  ev_target_range_charge_DC= UnitMapper("vehicleStatus.evStatus.reservChargeInfos.targetSOClist.0.dte.rangeByFuel.totalAvailableRange.value")
  some_other = UnitMapper("vehicleStatus.field","VehicleStatus.some_other_unit_field")

for key, value in UnitBasedFieldDefinition:
  setattr(vehicle, key, get_child_value(value.value_field), get_child_value(value.unit_field))

R3.3.10 makes that EU Hyundai no longer works compared to R3.3.8 because of "pushType": "APNS"

  • Hyundai / Kia Connect version: R3.3.10
  • Python version: 3.9.13
  • Operating System: Windows 10

Description

V3.3.8 fixed the EU Hyundai for this issue: #348
However, the changes to fix also EU Kia (V3.3.10) makes that it no longer works for EU Hyundai.

What I Did

"pushType": "APNS" is the problem for EU Hyundai, if I change it back to "pushType": "GCM", then it works again.
Apparently the pushType should be set dependent on EU Kia (APNS) or EU Hyundai (GCM).

Something like:

      if BRANDS[brand] == BRAND_KIA:
            self.PUSHTYPE : str = "APNS"
            .....
        elif BRANDS[brand] == BRAND_HYUNDAI:
            self.PUSHTYPE : str = "GCM"

.....
       "pushType": self.PUSHTYPE,

Below the exception for EU Hyundai when pushType is APNS.

DEBUG:urllib3.connectionpool:https://raw.githubusercontent.com:443 "GET /neoPix/bluelinky-stamps/master/hyundai-014d2225-8495-4735-812d-2616334fd15d.v2.json HTTP/1.1" 200 3107
DEBUG:hyundai_kia_connect_api.KiaUvoApiEU:hyundai_kia_connect_api - get_stamp 2023-07-03 13:01:59.949000+00:00 120000 46 998 46.495045125
DEBUG:hyundai_kia_connect_api.KiaUvoApiEU:hyundai_kia_connect_api - Get Device ID request: https://prd.eu-ccapi.hyundai.com:8080/api/v1/spa/notifications/register {'ccsp-service-id': '6d477c38-3ca4-4cf3-9557-2a1929a94654', 'ccsp-application-id': '014d2225-8495-4735-812d-2616334fd15d', 'Stamp': 'dGpcIp3dP0dLfkNRUItk/sCdmouaEMW4JAlLv76lGxrWLqMbn3rTaiKVMiTPgdM=', 'Content-Type': 'application/json;charset=UTF-8', 'Host': 'prd.eu-ccapi.hyundai.com:8080', 'Connection': 'Keep-Alive', 'Accept-Encoding': 'gzip', 'User-Agent': 'okhttp/3.12.0'} {'pushRegId': '4e4521ce7a988ee66de549dfa7e55260b419230c162dd1ba5299f854e3650859', 'pushType': 'APNS', 'uuid': 'ecc69a3a-ca82-4a0b-816a-47208aea1243'}
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): prd.eu-ccapi.hyundai.com:8080
DEBUG:urllib3.connectionpool:https://prd.eu-ccapi.hyundai.com:8080 "POST /api/v1/spa/notifications/register HTTP/1.1" 400 132
Traceback (most recent call last):
  File "C:\Users\Rick\git\monitor\debug.py", line 117, in <module>
    vm.check_and_refresh_token()
  File "C:\Users\Rick\git\monitor\hyundai_kia_connect_api\VehicleManager.py", line 120, in check_and_refresh_token
    self.initialize()
  File "C:\Users\Rick\git\monitor\hyundai_kia_connect_api\VehicleManager.py", line 64, in initialize
    self.token: Token = self.api.login(self.username, self.password)
  File "C:\Users\Rick\git\monitor\hyundai_kia_connect_api\KiaUvoApiEU.py", line 199, in login
    device_id = self._get_device_id(stamp)
  File "C:\Users\Rick\git\monitor\hyundai_kia_connect_api\KiaUvoApiEU.py", line 1107, in _get_device_id
    _check_response_for_errors(response)
  File "C:\Users\Rick\git\monitor\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 parameter.'

force_refresh_all_vehicles_states() - doesn't return odometer values

  • Hyundai / Kia Connect version: latest
  • Python version: 3.11
  • Operating System: Windows & Unix

Description

Using force_refresh_all_vehicles_states(self) method doesn't return odometer values (all "none").

Vehicle(id='xxx', name='KONA', model='KONA', registration_date='2021-10-20 17:59:26.158', year=None, VIN='xxx', key=None, enabled=True, _total_driving_range=369.0, _total_driving_range_value=369.0, _total_driving_range_unit='km', _odometer=None, _odometer_value=None, _odometer_unit=None, _geocode_address=None, _geocode_name=None, car_battery_percentage=80, engine_is_running=False, last_updated_at=datetime.datetime(2023, 3, 6, 9, 2, 12, tzinfo=tzfile('/usr/share/zoneinfo/Europe/Berlin')), timezone=None, dtc_count=None, dtc_descriptions=None, smart_key_battery_warning_is_on=False,...

Using update_all_vehicles_with_cached_state(self) works fine and returns odometer values.

Vehicle(id='xxx', name='KONA', model='KONA', registration_date='2021-10-20 17:59:26.158', year=None, VIN='xxx', key=None, enabled=True, _total_driving_range=394.0, _total_driving_range_value=394.0, _total_driving_range_unit='km', _odometer=22471.5, _odometer_value=22471.5, _odometer_unit='km', _geocode_address=None, _geocode_name=None, car_battery_percentage=85, engine_is_running=False, last_updated_at=datetime.datetime(2023, 3, 4, 16, 14, 21, tzinfo=tzfile('/usr/share/zoneinfo/Europe/Berlin')), timezone=None, dtc_count=None, dtc_descriptions=None, smart_key_battery_warning_is_on=False,...

It's a repeatable issue.
Is this a wanted/known behaviour?

hyundai_kia_connect_api.VehicleManager import fails

  • Hyundai / Kia Connect version: hyundai-kia-connect-api-1.31.0
  • Python version: 3.8.10
  • Operating System: Ubuntu Server 20.04 running on a ProxMox 7 LXC container

Description

I'm trying to run a very simple program to test whether I can login via the API but it already fails at the import statement.

What I Did

Code:

#!/usr/bin/python3
# -*- coding: utf-8 -*-

import os

from hyundai_kia_connect_api.VehicleManager import *

Output:

pi@ha[~/kia] ~/kia/login-test.py
Traceback (most recent call last):
  File "/home/pi/kia/login-test.py", line 6, in <module>
    from hyundai_kia_connect_api.VehicleManager import *
  File "/usr/local/lib/python3.8/dist-packages/hyundai_kia_connect_api/__init__.py", line 3, in <module>
    from .ApiImpl import ApiImpl, ClimateRequestOptions
  File "/usr/local/lib/python3.8/dist-packages/hyundai_kia_connect_api/ApiImpl.py", line 28, in <module>
    class ApiImpl:
  File "/usr/local/lib/python3.8/dist-packages/hyundai_kia_connect_api/ApiImpl.py", line 39, in ApiImpl
    def get_vehicles(self, token: Token) -> list[Vehicle]:
TypeError: 'type' object is not subscriptable

I left out the rest of the code since it didn't even make it past the import statement.

start_climat(): Temperature Question

  • Hyundai / Kia Connect version: 1.21.4

Description

I'm trying to get start_climat() working, but struggle with the set_temp.

What I Did

I tried the following:

        # https://github.com/Hacksore/bluelinky/issues/51#issue-658078545
        #options = ClimateRequestOptions(set_temp="22", duration=10, defrost=False, climate=False, heating=True)
        options = ClimateRequestOptions(set_temp="0FH", duration=10, climate=False, heating=True)
        vm.start_climate(id, options)

but get the following error:

  File "/home/user/PycharmProjects/bluelinx/venv/lib/python3.10/site-packages/hyundai_kia_connect_api/VehicleManager.py", line 94, in start_climate
    return self.api.start_climate(self.token, self.get_vehicle(vehicle_id), options)
  File "/home/user/PycharmProjects/bluelinx/venv/lib/python3.10/site-packages/hyundai_kia_connect_api/KiaUvoApiEU.py", line 362, in start_climate
    self.temperature_range.index(options.set_temp)
ValueError: '0FH' is not in list

I get the same error also when trying "22" as the set_temp value:
ValueError: '22' is not in list

What format/scale is used for the temperature control?

Thank you in advance.

(Kia EU) Push notification integration

It looks like an integration of Google Cloud Messaging was attempted at some point by @fuatakgun :

        try:
            credentials = push_receiver.register(sender_id=self.GCM_SENDER_ID)
            registration_id = credentials["gcm"]["token"]
        except:
            pass

push_register is a Google Cloud Messaging (GCM) / FIrebase Cloud Messaging (FCM) client library.
I assume the intended application was to retrieve push notifications the way the native app does it.

This was removed in new releases. Why?

Climate control no longer works after testing API

  • Hyundai / Kia Connect version: master

  • Python version: 3.10.5

  • Operating System: macOS Ventura 13.2

Description

Messing around with the master branch hoping to become a contributor. Wrote some tests for USA.

After playing around with it for a bit, suddenly bluelink won't start the climate anymore:

DEBUG    hyundai_kia_connect_api.HyundaiBlueLinkAPIUSA:HyundaiBlueLinkAPIUSA.py:511 hyundai_kia_connect_api - Start engine response: {"errorSubCode":"GEN","systemName":"BLODS","errorSubMessage":"Feature Status is OFF","errorMessage":"Your vehicle does not support this feature.","errorCode":502}

And now my actual Bluelink app will not start the car either.
Other functions still work, like lock/unlock and flashing lights.

What I Did

def test_something():
    vm = VehicleManager(
        region=3,
        brand=2,
        username=username,
        password=password,
        pin=pin,
        geocode_api_enable=True,
    )
    vm.check_and_refresh_token()
    vehicle_id = next(iter(vm.vehicles))
    vm.check_and_force_update_vehicles(force_refresh_interval=600)

	# this I changed several times before I realized it was broken in the Bluelink app as well... 
	# I don't know what the original command that started it all was. 
    vm.start_climate(vehicle_id, options=ClimateRequestOptions(set_temp=72, duration=10))

    print(vm.vehicles)
Testing started at 8:40 PM ...
Launching pytest with arguments --log-cli-level DEBUG us_login_test.py::test_something --no-header --no-summary -q in /Users/tylerthrailkill/Documents/dev/oss/hyundai_kia_connect_api/tests

============================= test session starts ==============================
collecting ... collected 1 item

us_login_test.py::test_something

============================== 1 passed in 0.96s ===============================

Process finished with exit code 0

-------------------------------- live log call ---------------------------------
DEBUG    hyundai_kia_connect_api.HyundaiBlueLinkAPIUSA:HyundaiBlueLinkAPIUSA.py:90 hyundai_kia_connect_api - initial API headers: {'content-type': 'application/json;charset=UTF-8', 'accept': 'application/json, text/plain, */*', 'accept-encoding': 'gzip, deflate, br', 'accept-language': 'en-US,en;q=0.9', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36', 'host': 'api.telematics.hyundaiusa.com', 'origin': 'https://api.telematics.hyundaiusa.com', 'referer': 'https://api.telematics.hyundaiusa.com/login', 'from': 'SPA', 'to': 'ISS', 'language': '0', 'offset': '-7', 'sec-fetch-dest': 'empty', 'sec-fetch-mode': 'cors', 'sec-fetch-site': 'same-origin', 'refresh': 'false', 'encryptFlag': 'false', 'brandIndicator': 'H', 'gen': '2', 'client_id': '***', 'clientSecret': '***'}
DEBUG    urllib3.connectionpool:connectionpool.py:1003 Starting new HTTPS connection (1): api.telematics.hyundaiusa.com:443
DEBUG    urllib3.connectionpool:connectionpool.py:456 https://api.telematics.hyundaiusa.com:443 "POST /v2/ac/oauth/token HTTP/1.1" 200 None
DEBUG    hyundai_kia_connect_api.HyundaiBlueLinkAPIUSA:HyundaiBlueLinkAPIUSA.py:102 hyundai_kia_connect_api - Sign In Response {"access_token":"***","refresh_token":"***","expires_in":"1799","username":"***@***.com"}
DEBUG    hyundai_kia_connect_api.HyundaiBlueLinkAPIUSA:HyundaiBlueLinkAPIUSA.py:107 hyundai_kia_connect_api - Access Token Value ***
DEBUG    hyundai_kia_connect_api.HyundaiBlueLinkAPIUSA:HyundaiBlueLinkAPIUSA.py:108 hyundai_kia_connect_api - Refresh Token Value ***
DEBUG    urllib3.connectionpool:connectionpool.py:456 https://api.telematics.hyundaiusa.com:443 "GET /ac/v2/enrollment/details/***@***.com HTTP/1.1" 200 None
DEBUG    hyundai_kia_connect_api.HyundaiBlueLinkAPIUSA:HyundaiBlueLinkAPIUSA.py:390 hyundai_kia_connect_api - Get Vehicles Response {"enrolledVehicleDetails":[{"packageDetails":[{"assetNumber":"A-S00516536","displayCategory":"Connected Care","packageId":"***","term":"36","renewalDate":"***","packageType":"Connected Care","startDate":"***"},{"assetNumber":"A-***","displayCategory":"Remote","packageId":"***","term":"36","renewalDate":"***","packageType":"Remote","startDate":"***"},{"assetNumber":"A-***","displayCategory":"Guidance","packageId":"***","term":"36","renewalDate":"***","packageType":"Guidance","startDate":"***"}],"driverDetails":[{"driverAddressDetails":[{"city":"***","postalCode":"***","type":"PRIMARY","region":"CO"}],"driver":{"accountId":"***","firstName":"***","lastName":"***","phonesOptIn":[],"tncId":"22","loginId":"***@***.com","preferredDealerCode":"***","driverUserProfile":"N","phones":[],"idmId":"***","userId":"***@***.com","email":"***@***.com"}}],"vehicleDetails":{"svrStatus":"NONE","dynamicBurgerMenu":"https://owners.hyundaiusa.com/content/dam/hyundai/us/myhyundai/image/2023/ioniq-5/limited/exterior/base/digital-teal/Dashboard-01.png/jcr:content/renditions/cq5dam.thumbnail.105.68.png","remoteStartWakeupDays":"seven","enrollmentDate":"***","svdDay":"11","trim":"LIMITED","modelCode":"IONIQ 5","ubiCapabilityInd":"Y","vin":"***","enrollmentId":"***","sideMirrorHeatCapable":"YES","ownersuccession":"1","odometer":"801","nickName":"2023 IONIQ 5","defaultBurgerMenu":"https://owners.hyundaiusa.com/content/dam/hyundai/us/myhyundai/image/2023/ioniq-5/limited/exterior/base/default/Dashboard-01.png/jcr:content/renditions/cq5dam.thumbnail.105.68.png","evStatus":"E","modelYear":"2023","steeringWheelHeatCapable":"YES","defaultDashboard":"https://owners.hyundaiusa.com/content/dam/hyundai/us/myhyundai/image/2023/ioniq-5/limited/exterior/base/default/Dashboard-01.png","vehicleGeneration":"2","starttype":"KEY","enrollmentType":"INDIVIDUAL","sapColorCode":"M9U","bluelinkEnabled":true,"odometerUpdateDate":"20230208191733","fatcAvailable":"Y","color":"TEAL","maintSyncCapable":"YES","brandIndicator":"H","deviceStatus":"ENROLLED","setOffPeak":"1","mapProvider":"HERE","generalBurgerMenu":"https://owners.hyundaiusa.com/content/dam/hyundai/us/myhyundai/image/2023/ioniq-5/general/exterior/base/default/Dashboard-01.png/jcr:content/renditions/cq5dam.thumbnail.105.68.png","interiorColor":"VKE","accessoryCode":"WAVN 5.0","nadid":"***","mit":"7500","regid":"***","blueLink":"Y","waypointInd":"NO","billingInd":"MONTHLY","dynamicDashboard":"https://owners.hyundaiusa.com/content/dam/hyundai/us/myhyundai/image/2023/ioniq-5/limited/exterior/base/digital-teal/Dashboard-01.png","imat":"7500","additionalVehicleDetails":{"temperatureRange":"true","tmuSleepMode":"No","enableHCAModule":"Y","maxTemp":81,"icpParking":0,"remoteLockConsentForRemoteStart":"Yes","calendarVehicleSyncEnable":"Yes","vehicleModemType":"4G","icpAACapable":"N","icpDriveThru":0,"dkType":"DK TYPE UNKNOWN","dynamicSOCText":"Use the slider above to set a charge limit. Charging will stop when this battery level is reached. The limit cannot be set lower than 50% This setting will override all other charge settings if set.","enableRoadSideAssitanceAAAModule":"Y","evAlarmOptionInfo":"Yes","mapOtaAccepted":"N","dkCapable":"Y","combinedHeatSettingsEnable":"N","icpChargingStation":0,"hyundaiHome":"N","wifiHotspotCapable":"N","dkEnrolled":"N","icpAvntCapable":"N","minTemp":63,"icpFuelStation":0,"targetSOCLevelMax":100,"remoteLockConsentForRemoteStartCapable":"Yes","icpCPCapable":"N","enableValetActivate":"N","energyConsoleCapable":"No"},"transmissiontype":"AUTO","bluelinkEnrolled":true,"targetSOCLevel":"50","rearWindowHeatCapable":"YES","preferredDealerCode":"CO032","hmaModel":"NE1","series":"IONIQ 5","enrollmentStatus":"ACTIVE","generalDashboard":"https://owners.hyundaiusa.com/content/dam/hyundai/us/myhyundai/image/2023/ioniq-5/general/exterior/base/default/Dashboard-01.png","userprofilestatus":"Y"},"roleDetails":[{"roleCode":"OWN","roleName":"OWNER"},{"roleCode":"SUB","roleName":"SUBSCRIBER"}],"responseHeaderMap":{}}],"addressDetails":[{"city":"***","street":"***","postalCode":"***","type":"PRIMARY","region":"CO"}],"emergencyContacts":[{"firstName":"***","lastName":"***","contactId":"***","phones":[{"number":"***","type":"mobile","order":1}],"relationship":"spouse","email":"***@***.com"}],"user":{"accountId":"**","firstName":"***","lastName":"***","phonesOptIn":[{"number":"***","primaryPhoneIndicator":"YES","fccOptIn":"YES","type":"MOBILE"}],"loginId":"***@***.com","additionalUserDetails":{"userProfileUpdate":"N","timezoneOffset":-7,"billingAccountNumber":"***","appRating":"N","geoLocationConsent":"Y","timezoneAbbr":"MST","otaAcceptance":"N","telematicsPhoneNumber":"***"},"tncFlag":"N","phones":[{"number":"***","type":"cell","order":1}],"idmId":"***","userId":"***@***.com","notificationEmail":"***@***.com","email":"***@***.com"}}
DEBUG    hyundai_kia_connect_api.HyundaiBlueLinkAPIUSA:HyundaiBlueLinkAPIUSA.py:458 hyundai_kia_connect_api - Start engine..
DEBUG    hyundai_kia_connect_api.HyundaiBlueLinkAPIUSA:HyundaiBlueLinkAPIUSA.py:468 hyundai_kia_connect_api - Start engine headers: {'content-type': 'application/json;charset=UTF-8', 'accept': 'application/json, text/plain, */*', 'accept-encoding': 'gzip, deflate, br', 'accept-language': 'en-US,en;q=0.9', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36', 'host': 'api.telematics.hyundaiusa.com', 'origin': 'https://api.telematics.hyundaiusa.com', 'referer': 'https://api.telematics.hyundaiusa.com/login', 'from': 'SPA', 'to': 'ISS', 'language': '0', 'offset': '-7', 'sec-fetch-dest': 'empty', 'sec-fetch-mode': 'cors', 'sec-fetch-site': 'same-origin', 'refresh': 'false', 'encryptFlag': 'false', 'brandIndicator': 'H', 'gen': '2', 'client_id': '***', 'clientSecret': '***', 'username': '***@***.com', 'accessToken': '***', 'vin': '***', 'registrationId': '***', 'blueLinkServicePin': '***'}
DEBUG    hyundai_kia_connect_api.HyundaiBlueLinkAPIUSA:HyundaiBlueLinkAPIUSA.py:505 hyundai_kia_connect_api - Start engine data: {'Ims': 0, 'airCtrl': 1, 'airTemp': {'unit': 1, 'value': 72}, 'defrost': False, 'heating1': 0, 'igniOnDuration': 10, 'seatHeaterVentInfo': {'drvSeatHeatState': 0, 'astSeatHeatState': 0, 'rlSeatHeatState': 0, 'rrSeatHeatState': 0}, 'username': '***@***.com', 'vin': '***'}
DEBUG    urllib3.connectionpool:connectionpool.py:456 https://api.telematics.hyundaiusa.com:443 "POST /ac/v2/rcs/rsc/start HTTP/1.1" 502 None
DEBUG    hyundai_kia_connect_api.HyundaiBlueLinkAPIUSA:HyundaiBlueLinkAPIUSA.py:508 hyundai_kia_connect_api - Start engine response status code: 502
DEBUG    hyundai_kia_connect_api.HyundaiBlueLinkAPIUSA:HyundaiBlueLinkAPIUSA.py:511 hyundai_kia_connect_api - Start engine response: {"errorSubCode":"GEN","systemName":"BLODS","errorSubMessage":"Feature Status is OFF","errorMessage":"Your vehicle does not support this feature.","errorCode":502}
PASSED                                                                   [100%]{'***': Vehicle(id='***', name='2023 IONIQ 5', model='IONIQ 5', registration_date=['enrollmentDate'], year=None, VIN='***', key=None, enabled=True, _total_driving_range=None, _total_driving_range_value=None, _total_driving_range_unit=None, _odometer=None, _odometer_value=None, _odometer_unit=None, _geocode_address=None, _geocode_name=None, car_battery_percentage=None, engine_is_running=None, last_updated_at=None, timezone=None, dtc_count=None, dtc_descriptions=None, smart_key_battery_warning_is_on=None, washer_fluid_warning_is_on=None, brake_fluid_warning_is_on=None, _air_temperature=None, _air_temperature_value=None, _air_temperature_unit=None, air_control_is_on=None, defrost_is_on=None, steering_wheel_heater_is_on=None, back_window_heater_is_on=None, side_mirror_heater_is_on=None, front_left_seat_status=None, front_right_seat_status=None, rear_left_seat_status=None, rear_right_seat_status=None, is_locked=None, front_left_door_is_open=None, front_right_door_is_open=None, back_left_door_is_open=None, back_right_door_is_open=None, trunk_is_open=None, hood_is_open=None, tire_pressure_all_warning_is_on=None, tire_pressure_rear_left_warning_is_on=None, tire_pressure_front_left_warning_is_on=None, tire_pressure_front_right_warning_is_on=None, tire_pressure_rear_right_warning_is_on=None, _next_service_distance=None, _next_service_distance_value=None, _next_service_distance_unit=None, _last_service_distance=None, _last_service_distance_value=None, _last_service_distance_unit=None, _location_latitude=None, _location_longitude=None, _location_last_set_time=None, ev_charge_port_door_is_open=None, ev_charge_limits_dc=None, ev_charge_limits_ac=None, total_power_consumed=None, power_consumption_30d=None, daily_stats=[], month_trip_info=None, day_trip_info=None, ev_battery_percentage=None, ev_battery_is_charging=None, ev_battery_is_plugged_in=None, _ev_driving_range=None, _ev_driving_range_value=None, _ev_driving_range_unit=None, _ev_estimated_current_charge_duration=None, _ev_estimated_current_charge_duration_value=None, _ev_estimated_current_charge_duration_unit=None, _ev_estimated_fast_charge_duration=None, _ev_estimated_fast_charge_duration_value=None, _ev_estimated_fast_charge_duration_unit=None, _ev_estimated_portable_charge_duration=None, _ev_estimated_portable_charge_duration_value=None, _ev_estimated_portable_charge_duration_unit=None, _ev_estimated_station_charge_duration=None, _ev_estimated_station_charge_duration_value=None, _ev_estimated_station_charge_duration_unit=None, _ev_target_range_charge_AC=None, _ev_target_range_charge_AC_value=None, _ev_target_range_charge_AC_unit=None, _ev_target_range_charge_DC=None, _ev_target_range_charge_DC_value=None, _ev_target_range_charge_DC_unit=None, ev_first_departure_enabled=None, ev_second_departure_enabled=None, ev_first_departure_days=None, ev_second_departure_days=None, ev_first_departure_time=None, ev_second_departure_time=None, ev_off_peak_start_time=None, ev_off_peak_end_time=None, ev_off_peak_charge_only_enabled=None, _fuel_driving_range=None, _fuel_driving_range_value=None, _fuel_driving_range_unit=None, fuel_level=None, fuel_level_is_low=None, engine_type=None, data=None)}

dt.datetime.strptime(value, "%I%M %p").time() throws TypeError

  • Hyundai / Kia Connect version: ?
  • Python version: 3.10
  • Operating System: ?

Description

Error encountered by @Adi3000, see #255

when vehicle.ev_first_departure_time is fetch _get_time_from_string isn't retreivable because of :

File "/usr/local/lib/python3.10/dist-packages/hyundai_kia_connect_api/KiaUvoApiEU.py", line 587, in _update_vehicle_properties
vehicle.ev_first_departure_time = self._get_time_from_string(
File "/usr/local/lib/python3.10/dist-packages/hyundai_kia_connect_api/KiaUvoApiEU.py", line 276, in _get_time_from_string
value = dt.datetime.strptime(value, "%I%M %p").time()
TypeError: 'NoneType' object is not callable

See my reply here: #255 (comment)

Missing ServiceTemporaryUnavailable Exception in KiaUvoApiEU.py

  • Hyundai / Kia Connect version: v2.4.0
  • Python version: 3.9.13
  • Operating System: Windows 10

Description

In my program I want to catch known exceptions and for unknown or too general exceptions I want to print a stacktrace.
Currently I do not distinguish between the different exceptions and so always print a stacktrace.

So I started with the following approach:

    def handle_exception(ex: Exception, retries: int, stacktrace=False):
    """
    If an error is found, an exception is raised.
    retCode known values:
    - S: success
    - F: failure
    resCode / resMsg known values:
    - 0000: no error
    - 4004: "Duplicate request"
    - 4081: "Request timeout"
    - 5031: "Unavailable remote control - Service Temporary Unavailable"
    - 5091: "Exceeds number of requests"
    - 5921: "No Data Found v2 - No Data Found v2"
    - 9999: "Undefined Error - Response timeout"
    """
    exception_str = str(ex)
    log(f"Exception: {exception_str}")
    if stacktrace:
        traceback.print_exc()
    retries -= 1
    sleep(retries)
    return retries



        try:

           ..... do the hyundai_kia_connect_api calls.....

        except exceptions.AuthenticationError as ex:
            retries = handle_exception(ex, retries)
        except exceptions.RateLimitingError as ex:
            retries = handle_exception(ex, retries)
        except exceptions.NoDataFound as ex:
            retries = handle_exception(ex, retries)
        except exceptions.DuplicateRequestError as ex:
            retries = handle_exception(ex, retries)
        except exceptions.RequestTimeoutError as ex:
            retries = handle_exception(ex, retries)
        except exceptions.InvalidAPIResponseError as ex:
            retries = handle_exception(ex, retries, True)
        except exceptions.APIError as ex:
            retries = handle_exception(ex, retries, True)
        except exceptions.HyundaiKiaException as ex:
            retries = handle_exception(ex, retries, True)
        except Exception as ex:  # pylint: disable=broad-except
            retries = handle_exception(ex, retries, True)

However, it appears that - 5031: "Unavailable remote control - Service Temporary Unavailable" is mapped to the generic APIError:

"5031": APIError,

I would expect a specific exception in exception.py, e.g. ServiceTemporaryUnavailable so I could catch that specific exception too and could add to my code:

        except exceptions.ServiceTemporaryUnavailable as ex:
            retries = handle_exception(ex, retries)

What I Did

I patched exceptions.py with ServiceTemporaryUnavailable and also changed KiaUvoApiEU.py to that exception.
Is there a reason APIError is thrown and not a specific exception is made?

Since 3 days: Unexpected exception KeyError: 'redirectUrl'

First, thank you very much for this great compinent, I use it almost every day.

  • Hyundai / Kia Connect version: 2.0.9
  • Python version: 3.10
  • Operating System: Gentoo Linux / HomeAssistant (Core)

Description

Cannot connect to european cloud service since 3 days.
Used Account was created in early October 2022.

What I Did

Home Assistant was stuck on 3 day old data.
Restarted HA, and all entities from the integration showed unavailable.

Had an older custom_component (from late September 22),
so I replaced it with the current one and installed hyundai-kia-connect-api-3.1.2.
Same error persisted, only line numbers changed.

Logged out from the App, and logged back in, restarted HA, nothing changed.
Removed HA's Integration and tried to re-add it,
during Login (with the new version):

2023-04-07 17:01:55.816 ERROR (MainThread) [custom_components.kia_uvo.config_flow] Unexpected exception
Traceback (most recent call last):
  File "/usr/lib/python3.10/site-packages/hyundai_kia_connect_api/KiaUvoApiEU.py", line 203, in login
    authorization_code = self._get_authorization_code_with_redirect_url(
  File "/usr/lib/python3.10/site-packages/hyundai_kia_connect_api/KiaUvoApiEU.py", line 1146, 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 "/etc/homeassistant/custom_components/kia_uvo/config_flow.py", line 159, in async_step_user
    await validate_input(self.hass, user_input)
  File "/etc/homeassistant/custom_components/kia_uvo/config_flow.py", line 63, in validate_input
    token: Token = await hass.async_add_executor_job(
  File "/usr/lib/python3.10/concurrent/futures/thread.py", line 58, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/usr/lib/python3.10/site-packages/hyundai_kia_connect_api/KiaUvoApiEU.py", line 208, in login
    authorization_code = self._get_authorization_code_with_form(
  File "/usr/lib/python3.10/site-packages/hyundai_kia_connect_api/KiaUvoApiEU.py", line 1242, in _get_authorization_code_with_form
    intUserId = "".join(parse_qs(parsed_url.query)["intUserId"])
KeyError: 'intUserId'

Old error with previous custom integration:

2023-04-07 07:57:05.801 ERROR (MainThread) [homeassistant] Error doing job: Task exception was never retrieved
Traceback (most recent call last):
  File "/etc/homeassistant/custom_components/kia_uvo/KiaUvoApiEU.py", line 125, in login
    self.authorization_code = self.get_authorization_code_with_redirect_url()
  File "/etc/homeassistant/custom_components/kia_uvo/KiaUvoApiEU.py", line 247, 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 "/etc/homeassistant/custom_components/kia_uvo/__init__.py", line 187, in update
    await vehicle.refresh_token()
  File "/etc/homeassistant/custom_components/kia_uvo/Vehicle.py", line 178, in refresh_token
    await self.hass.async_add_executor_job(self.login)
  File "/usr/lib/python3.10/concurrent/futures/thread.py", line 58, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/etc/homeassistant/custom_components/kia_uvo/Vehicle.py", line 253, in login
    self.token = self.kia_uvo_api.login()
  File "/etc/homeassistant/custom_components/kia_uvo/KiaUvoApiEU.py", line 127, in login
    self.authorization_code = self.get_authorization_code_with_form()
  File "/etc/homeassistant/custom_components/kia_uvo/KiaUvoApiEU.py", line 343, in get_authorization_code_with_form
    intUserId = "".join(parse_qs(parsed_url.query)["intUserId"])
KeyError: 'intUserId'

Spelling error

Spelling error in:
hyundai_kia_connect_api/hyundai_kia_connect_api/KiaUvoApiEU.py

Line 339, it says seat_staus instead of seat_status

 vehicle.rear_left_seat_staus = SEAT_STATUS[get_child_value(
            state, "vehicleStatus.seatHeaterVentState.rlSeatHeatState"
        )]
        vehicle.rear_right_seat_status = SEAT_STATUS[get_child_value(
            state, "vehicleStatus.seatHeaterVentState.rrSeatHeatState"
        )]

Error on Check_and_refresh_token

Getting "string indices must be integers" error on Check_and_refresh_token.

Started happening today. Seems like they did some kind of update for Kia app yesterday, as the app was down for a couple of hours.

CA no seat heating function

  • Hyundai / Kia Connect version: 1.45.6
  • Python version: 3.9
  • Operating System: HAOS

Description

I was trying to get the seat heating work for the start_climate function.

What I Did

I changed the KiaUvoApiCA.py file line number 495 to the following and it worked. (Non EV)
Steeling wheel heating: On
Front and back defrost: On
Driver Seat: HI heat, All other off.

Was using burp to capture the API call.

payload = {
            "setting": {
                "airCtrl": int(climate),
                "defrost": defrost,
                "heating1": 4,
                "igniOnDuration": duration,
                "ims": 0,
                "airTemp": {"value": set_temp, "unit": 0, "hvacTempType": 1},
                "seatHeaterVentCMD":{"drvSeatOptCmd":8, "astSeatOptCmd":2, "rlSeatOptCmd":2, "rrSeatOptCmd":2},
            },
            "pin": self.pin,
        }

Any chance it could be added to the API? I usually just change the KiaUvoApiCA.py each time when this pip package get updates.

Thanks!

[EU] Login fails: "Invalid request body - Invalid parameter."

  • Hyundai / Kia Connect version: 3.3.7
  • Python version: 3.9.17
  • Operating System: Linux

Description

Error at login:

Traceback (most recent call last):
  File "/root/kia-hyundai-tracker/VehicleClient.py", line 251, in loop
    self.vm.check_and_refresh_token()
  File "/root/kia-hyundai-tracker/venv/lib/python3.9/site-packages/hyundai_kia_connect_api/VehicleManager.py", line 120, in check_and_refresh_token
    self.initialize()
  File "/root/kia-hyundai-tracker/venv/lib/python3.9/site-packages/hyundai_kia_connect_api/VehicleManager.py", line 64, in initialize
    self.token: Token = self.api.login(self.username, self.password)
  File "/root/kia-hyundai-tracker/venv/lib/python3.9/site-packages/hyundai_kia_connect_api/KiaUvoApiEU.py", line 198, in login
    device_id = self._get_device_id(stamp)
  File "/root/kia-hyundai-tracker/venv/lib/python3.9/site-packages/hyundai_kia_connect_api/KiaUvoApiEU.py", line 1104, in _get_device_id
    _check_response_for_errors(response)
  File "/root/kia-hyundai-tracker/venv/lib/python3.9/site-packages/hyundai_kia_connect_api/KiaUvoApiEU.py", line 110, in _check_response_for_errors
    raise APIError(f"Server returned: '{response['resMsg']}'")
hyundai_kia_connect_api.exceptions.APIError: Server returned: 'Invalid request body - Invalid parameter.'

The native mobile app still works: tested logout -> login -> force refresh.

Error in ApiImpl.py

  • Hyundai / Kia Connect version: 1.34.1
  • Python version: 3.8.10
  • Operating System: ubuntu xernial

Description

simple by including from hyundai_kia_connect_api import * i get a python error

What I Did

Traceback (most recent call last):
  File "1", line 1, in <module>
    from hyundai_kia_connect_api import *
  File "/u/src/hyundai_kia_connect_api-1.34.1/hyundai_kia_connect_api/__init__.py", line 3, in <module>
    from .ApiImpl import ApiImpl, ClimateRequestOptions
  File "/u/src/hyundai_kia_connect_api-1.34.1/hyundai_kia_connect_api/ApiImpl.py", line 27, in <module>
    class ApiImpl:
  File "/u/src/hyundai_kia_connect_api-1.34.1/hyundai_kia_connect_api/ApiImpl.py", line 38, in ApiImpl
    def get_vehicles(self, token: Token) -> list[Vehicle]:
TypeError: 'type' object is not subscriptable

API Rate Limit or 24h "bug"?

  • Hyundai / Kia Connect version: 1.21.6

Description

My MQTT loop runs fine for 24h + ~13 mins, but after that I don't receive any update anymore.
My loop sleeps for 10 mins between updates resulting in about 144 requests/24h which should leave enough headroom for "manual" bluelink app usage and start_climat calls.

I works again after restarting my script.

Any ideas?

What I Did

Traceback (most recent call last):
  File "/home/user/PycharmProjects/bluelinx/main.py", line 152, in <module>
    update_data()
  File "/home/user/PycharmProjects/bluelinx/main.py", line 39, in update_data
    vm.check_and_force_update_vehicles(600)
  File "/home/user/PycharmProjects/bluelinx/venv/lib/python3.10/site-packages/hyundai_kia_connect_api/VehicleManager.py", line 74, in check_and_force_update_vehicles
    self.update_vehicle_with_cached_state(vehicle)
  File "/home/user/PycharmProjects/bluelinx/venv/lib/python3.10/site-packages/hyundai_kia_connect_api/VehicleManager.py", line 61, in update_vehicle_with_cached_state
    self.api.update_vehicle_with_cached_state(self.token, vehicle)
  File "/home/user/PycharmProjects/bluelinx/venv/lib/python3.10/site-packages/hyundai_kia_connect_api/KiaUvoApiEU.py", line 171, in update_vehicle_with_cached_state
    state = self._get_cached_vehicle_state(token, vehicle)
  File "/home/user/PycharmProjects/bluelinx/venv/lib/python3.10/site-packages/hyundai_kia_connect_api/KiaUvoApiEU.py", line 312, in _get_cached_vehicle_state
    return response["resMsg"]["vehicleStatusInfo"]
KeyError: 'resMsg'

Start/Stop climate doesn't work

  • Hyundai / Kia Connect version: 3.3.7
  • Python version: 3.11-alpine
  • Operating System: Docker image 3.11-alpine

Description

I try to start climate on my Hyundai Santa Fe but it doesn't work :/
Command return timeout after 60s

What I Did

import logging
from time import sleep

from hyundai_kia_connect_api import VehicleManager, ClimateRequestOptions


class Bluelinky:
    def __init__(self, vin, region, brand, username, password, pin, language="fr", geocode_api_enable=True,
                 geocode_api_use_email=True):
        self.timeout = 60
        self.vin = vin
        self.vm = VehicleManager(
            region=int(region),
            brand=int(brand),
            username=username,
            password=password,
            pin=pin,
            geocode_api_enable=geocode_api_enable,
            geocode_api_use_email=geocode_api_use_email,
            language=language
        )
        self.vehicle_id = None
        self.action_id = None

        self.vm.check_and_refresh_token()
        self.vm.update_all_vehicles_with_cached_state()
        self.found_vehicule()

    def found_vehicule(self):
        for vehicle_id, data in self.vm.vehicles.items():
            if self.vin == data.VIN:
                self.vehicle_id = data.id

    def waiting(self):
        retry = 10
        ack = False
        waiting_time = 0
        while not ack:
            status = self.vm.check_action_status(vehicle_id=self.vehicle_id, action_id=self.action_id)
            logging.info(f'=>{status}<=')
            if str(status) == "OrderStatus.SUCCESS":
                logging.info("command success")
                ack = True
            else:
                if waiting_time >= self.timeout:
                    logging.error("command error (timeout)")
                    ack = True
                sleep(retry)
                waiting_time = waiting_time + retry

    def unlock(self):
        self.action_id = self.vm.unlock(self.vehicle_id)
        self.waiting()

    def lock(self):
        self.action_id = self.vm.lock(self.vehicle_id)
        self.waiting()

    def climate(self):
        self.action_id = self.vm.start_climate(self.vehicle_id, ClimateRequestOptions(
            set_temp=23,
            duration=10,
            defrost=False,
            climate=True,
            heating=True,
            front_left_seat=False,
            front_right_seat=False,
            rear_left_seat=False,
            rear_right_seat=False,
        ))
        self.waiting()

BLUELINK = Bluelinky(
    vin="XXXXXXXXXXXXXXXX",
    region=int(BLUELINK_CONFIG["region"]),
    brand=int(BLUELINK_CONFIG["brand"]),
    username=BLUELINK_CONFIG["username"],
    password=BLUELINK_CONFIG["password"],
    pin=BLUELINK_CONFIG["pin"],
    geocode_api_enable=True,
    geocode_api_use_email=True,
    language="fr"
)
# BLUELINK.lock() => It's WORK
BLUELINK.climate() => TIMEOUT

Log :

2023-06-13 01:23:37.465 -     INFO : Check XXXXXXXXXXXXXXXX
2023-06-13 01:23:42.823 -     INFO : Action status not set yet by server - try again in a few seconds
2023-06-13 01:23:42.824 -     INFO : =>OrderStatus.PENDING<=
2023-06-13 01:23:53.046 -     INFO : Action status not set yet by server - try again in a few seconds
2023-06-13 01:23:53.046 -     INFO : =>OrderStatus.PENDING<=
2023-06-13 01:24:03.212 -     INFO : Action status not set yet by server - try again in a few seconds
2023-06-13 01:24:03.212 -     INFO : =>OrderStatus.PENDING<=
2023-06-13 01:24:13.451 -     INFO : Action status not set yet by server - try again in a few seconds
2023-06-13 01:24:13.451 -     INFO : =>OrderStatus.PENDING<=
2023-06-13 01:24:24.120 -     INFO : Action status not set yet by server - try again in a few seconds
2023-06-13 01:24:24.120 -     INFO : =>OrderStatus.PENDING<=
2023-06-13 01:24:34.508 -     INFO : Action status not set yet by server - try again in a few seconds
2023-06-13 01:24:34.508 -     INFO : =>OrderStatus.PENDING<=
2023-06-13 01:24:45.682 -     INFO : Action status not set yet by server - try again in a few seconds
2023-06-13 01:24:45.682 -     INFO : =>OrderStatus.PENDING<=
2023-06-13 01:24:45.682 -    ERROR : command error (timeout)

Instructions how to use

Please add some pointers in the usage documentation as in how to you the module.

Apart from hyundai_kia_connect_api :

  • sample code for the parameters (especially region and brand)
  • sample code to initialise the module
  • sample code to eg. request status

Genesis Integration

  • Hyundai / Kia Connect version:

Request

Since Genesis has with the GV60 the Same Plattform and Infotainment as the EV6 and Ionic 5. Should this connect_API aswell work with the Genesis Car?
I will get mine in 5 Months so I'm just asking if this would be availible, since it should be the same?

Can trip information shown in BLUELINK app been made available?

Hyundai / Kia Connect version: latest
Python version: 3.11
Operating System: Windows & Unix

Description

Would be greate to have individual trip data made available the the api.
I'm referring to the data that is shown in the BLUELINK app in the menu section: /MORE/My trips/...

What I Did

I couldn't find any of the trip data in the payload of the API services.

Example code in README wrong, so the server is called too often, were less calls would be sufficient?

  • Hyundai / Kia Connect version: v1.52.13
  • Python version: 3.9.13
  • Operating System: Windows 10

Description

The usage information (README) contains the following example:

vm = VehicleManager(region=2, brand=1, username="[email protected]", password="password", pin="1234")
vm.check_and_refresh_token()
vm.update_all_vehicles_with_cached_state()
print(vm.vehicles)

However, if I do not call "vm.update_all_vehicles_with_cached_state()" I still get the cached values.
So it looks like this call is not needed when you only want the cached server values.

Do I overlook thinks?
Note that I have an IONIQ 5 in Europe, so maybe there are side effects for other REGIONS not doing this call?

Especially because the number of calls to the server are restricted (200 in Europe), having less calls is important. Other regions are even more restricted, so even more important.

What I Did

I used the following tool debug.py and commented the line:

vm.update_all_vehicles_with_cached_state()

The output (except for the debug logging of calls) is exactly the same with or without the call. Note that I always run the script once (do not keep the program alive), so I always need to call:

vm.check_and_refresh_token()

AttributeError: 'Token' object has no attribute 'vehicle_id' when calling check_and_refresh_token()

  • Hyundai / Kia Connect version: 1.26.5
  • Python version: 3.9
  • Operating System: macOS 12.1

Description

I'm getting an attribute error - 'Token' object has no attribute 'vehicle_id' -- when calling VehicleManager.check_and_refresh_token().

Looking at the source, I think it's because vehicle_id is an attibute on Vehicle, not on Token; I think this is a bug in HyundaiBlueLinkAPIUSA.py, line 293 -- I believe that should read headers["vehicleId"] = vehicle.id?

I'll try to open a PR, but I wanted to open the issue in case my theory is wrong.

What I Did

>>> import hyundai_kia_connect_api as hkapi
>>> vm = hkapi.VehicleManager(
...     region=3,
...     brand=2,
...     username="[email protected]",
...     password="xxx",
...     pin="xxx",
... )
>>> vm.check_and_refresh_token()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/jacob/Library/Caches/pypoetry/virtualenvs/ioniq-U4yWA9lt-py3.9/lib/python3.9/site-packages/hyundai_kia_connect_api/VehicleManager.py", line 86, in check_and_refresh_token
    self.initialize()
  File "/Users/jacob/Library/Caches/pypoetry/virtualenvs/ioniq-U4yWA9lt-py3.9/lib/python3.9/site-packages/hyundai_kia_connect_api/VehicleManager.py", line 51, in initialize
    self.update_all_vehicles_with_cached_state()
  File "/Users/jacob/Library/Caches/pypoetry/virtualenvs/ioniq-U4yWA9lt-py3.9/lib/python3.9/site-packages/hyundai_kia_connect_api/VehicleManager.py", line 58, in update_all_vehicles_with_cached_state
    self.update_vehicle_with_cached_state(self.get_vehicle(vehicle_id))
  File "/Users/jacob/Library/Caches/pypoetry/virtualenvs/ioniq-U4yWA9lt-py3.9/lib/python3.9/site-packages/hyundai_kia_connect_api/VehicleManager.py", line 61, in update_vehicle_with_cached_state
    self.api.update_vehicle_with_cached_state(self.token, vehicle)
  File "/Users/jacob/Library/Caches/pypoetry/virtualenvs/ioniq-U4yWA9lt-py3.9/lib/python3.9/site-packages/hyundai_kia_connect_api/HyundaiBlueLinkAPIUSA.py", line 158, in update_vehicle_with_cached_state
    state = self._get_cached_vehicle_state(token, vehicle)
  File "/Users/jacob/Library/Caches/pypoetry/virtualenvs/ioniq-U4yWA9lt-py3.9/lib/python3.9/site-packages/hyundai_kia_connect_api/HyundaiBlueLinkAPIUSA.py", line 154, in _get_cached_vehicle_state
    vehicle_status["vehicleLocation"] = self.get_location(token, vehicle)
  File "/Users/jacob/Library/Caches/pypoetry/virtualenvs/ioniq-U4yWA9lt-py3.9/lib/python3.9/site-packages/hyundai_kia_connect_api/HyundaiBlueLinkAPIUSA.py", line 293, in get_location
    headers["vehicleId"] = token.vehicle_id
AttributeError: 'Token' object has no attribute 'vehicle_id'
>>>

Use api for dynamic battery loading

Thanks for this interesting api. I own a Kia eNiro and intend to make a python application that supports dynamic battery loading. Besides figures from my P1 port and sun power forecast (Solcast) I need the actual battery capacity of the Kia. I think I can extract this from the api (car_battery_percentage, ev_battery_percentage, _ev_driving_range), but I have been puzzling how to do this without using home assistant. I succeeded to populate the address of the vehicle in the vehicle instance as described in the Read_me. Can you please provide me with some example code to read these figures just using Python?

pypi Doesn't Auto Run

Looks like the release trigger doesn't work for pypi which can make it out of sync with this repo.

from locale import D_T_FMT

  • Hyundai / Kia Connect version: 1.34.2
  • Python version: 3.9.13
  • Operating System: Windows 10

Description

The following import gives an error while interpreting:

hyundai_kia_connect_api\HyundaiBlueLinkAPIUSA.py:1:from locale import D_T_FMT

C:\Users\Rick\git\monitor>python monitor.py
Traceback (most recent call last):
File "C:\Users\Rick\git\monitor\monitor.py", line 38, in
from hyundai_kia_connect_api import VehicleManager
File "C:\Users\Rick\git\monitor\hyundai_kia_connect_api_init_.py", line 4, in
from .HyundaiBlueLinkAPIUSA import HyundaiBlueLinkAPIUSA
File "C:\Users\Rick\git\monitor\hyundai_kia_connect_api\HyundaiBlueLinkAPIUSA.py", line 1, in
from locale import D_T_FMT

ImportError: cannot import name 'D_T_FMT' from 'locale' (C:\Users\Rick\AppData\Local\Programs\Python\Python39\lib\locale.py)

What I Did

If I comment the line (it is not used in the source code!), everything runs fine.
What package should have been installed to have this "from locale import D_T_FMT working"?
What was the intention of this import statement?

Research

Appears that this D_T_FMT is not available on Windows according to this question:
https://stackoverflow.com/questions/14103365/python-elegant-bypass-to-not-having-locale-d-t-fmt-on-windows

Because it is NOT used, removing the import statement would be the solution I guess.

name 'location' is not defined

  • Hyundai / Kia Connect version: 1.34.1
  • Python version: 3.9
  • Operating System: Raspberry OS

Description

The sample code on Hyundai EU returns "name 'location' is not defined"
I used a real account.

What I Did

from hyundai_kia_connect_api import VehicleManager
vm = VehicleManager(region=1,
                    brand=2,
                    username="[email protected]",
                    password="testtest",
                    pin="")
vm.check_and_refresh_token()
vm.update_all_vehicles_with_cached_state()
print(vm.vehicles)

returns:

hyundai_kia_connect_api - Get vehicle location failed
Traceback (most recent call last):
  File "/home/pi/hyundai_api.py", line 7, in <module>
    vm.check_and_refresh_token()
  File "/home/pi/.local/lib/python3.9/site-packages/hyundai_kia_connect_api/VehicleManager.py", line 88, in check_and_refresh_token
    self.initialize()
  File "/home/pi/.local/lib/python3.9/site-packages/hyundai_kia_connect_api/VehicleManager.py", line 51, in initialize
    self.update_all_vehicles_with_cached_state()
  File "/home/pi/.local/lib/python3.9/site-packages/hyundai_kia_connect_api/VehicleManager.py", line 58, in update_all_vehicles_with_cached_state
    self.update_vehicle_with_cached_state(self.get_vehicle(vehicle_id))
  File "/home/pi/.local/lib/python3.9/site-packages/hyundai_kia_connect_api/VehicleManager.py", line 61, in update_vehicle_with_cached_state
    self.api.update_vehicle_with_cached_state(self.token, vehicle)
  File "/home/pi/.local/lib/python3.9/site-packages/hyundai_kia_connect_api/KiaUvoApiEU.py", line 315, in update_vehicle_with_cached_state
    self.get_last_updated_at(get_child_value(location, "vehicleLocation.time")),
NameError: name 'location' is not defined

hyundai_kia_connect_api - _get_location failed

  • Hyundai / Kia Connect version: 3.1.7
  • Python version: 3.9
  • Operating System: Ubuntu 22.04

Description

I'm trying to use the geo location feature while extracting trip info. I'm getting the following warning: "hyundai_kia_connect_api - _get_location failed"

The vehicle manager is constructed as follows:

   vm = VehicleManager(
        brand=1,
        region=1,
        username=kia.username,
        password=kia.password,
        pin=kia.pin,
        geocode_api_enable=True,
        geocode_api_use_email=True
    )

What is the proper way to extract the geo location info per trip?

Precision of range and total driving range has too many digits.

  • Hyundai / Kia Connect version: 2.3.1
  • Python version: 3.10
  • Operating System:
    ** Home Assistant 2022.12.8
    ** Supervisor 2022.11.2
    ** Operating System 9.4
    ** Frontend 20221213.1 - latest

Description

Precision of range and total driving range has too many digits.
For example:

IONIQ EV Total Driving Range
32 minutes ago
106.2524272 mi

What I Did

Viewed the values in Home Assistant.
Precision is too great.

Preferably something like two decimal places (certainly no more).

Unknown keys

I am using the Kia EU API (e-niro 2020)
Wondering what these keys represent in the response to /status/latest:

  • ign3 (bool)
  • sleepModeCheck (bool)
  • tailLampStatus (int)
  • systemCutOffAlert (int)
  • hazardStatus (int)
  • remoteWaitingTimeAlert (dict)
  • battery.batState (int)
  • airTemp.hvacTempType (int)
  • acc (bool)
  • transCond (bool)

If I can be of any help to investigate, let me know.

Full response:

  'vehicleLocation': {
    'coord': {
      'lat': 43.422603,
      'lon': 5.288278,
      'alt': 0,
      'type': 0
    },
    'head': 40,
    'speed': {
      'value': 0,
      'unit': 1
    },
    'accuracy': {
      'hdop': 0,
      'pdop': 0
    },
    'time': '20221116143811'
  },
  'vehicleStatus': {
    'airCtrlOn': False,
    'engine': False,
    'doorLock': False,
    'doorOpen': {
      'frontLeft': 0,
      'frontRight': 0,
      'backLeft': 0,
      'backRight': 0
    },
    'trunkOpen': False,
    'airTemp': {
      'value': '02H',
      'unit': 0,
      'hvacTempType': 1
    },
    'defrost': False,
    'acc': False,
    'evStatus': {
      'batteryCharge': False,
      'batteryStatus': 62,
      'batteryPlugin': 0,
      'remainTime2': {
        'etc1': {
          'value': 21,
          'unit': 1
        },
        'etc2': {
          'value': 630,
          'unit': 1
        },
        'etc3': {
          'value': 205,
          'unit': 1
        },
        'atc': {
          'value': 630,
          'unit': 1
        }
      },
      'drvDistance': [
        {
          'rangeByFuel': {
            'evModeRange': {
              'value': 271,
              'unit': 1
            },
            'totalAvailableRange': {
              'value': 271,
              'unit': 1
            }
          },
          'type': 2
        }
      ],
      'reservChargeInfos': {
        'reservChargeInfo': {
          'reservChargeInfoDetail': {
            'reservInfo': {
              'day': [
                9
              ],
              'time': {
                'time': '1200',
                'timeSection': 0
              }
            },
            'reservChargeSet': False,
            'reservFatcSet': {
              'defrost': False,
              'airTemp': {
                'value': '00H',
                'unit': 0,
                'hvacTempType': 1
              },
              'airCtrl': 0,
              'heating1': 0
            }
          }
        },
        'offpeakPowerInfo': {
          'offPeakPowerTime1': {
            'starttime': {
              'time': '1200',
              'timeSection': 0
            },
            'endtime': {
              'time': '1200',
              'timeSection': 0
            }
          },
          'offPeakPowerFlag': 0
        },
        'reserveChargeInfo2': {
          'reservChargeInfoDetail': {
            'reservInfo': {
              'day': [
                9
              ],
              'time': {
                'time': '1200',
                'timeSection': 0
              }
            },
            'reservChargeSet': False,
            'reservFatcSet': {
              'defrost': False,
              'airTemp': {
                'value': '00H',
                'unit': 0,
                'hvacTempType': 1
              },
              'airCtrl': 0,
              'heating1': 0
            }
          }
        },
        'reservFlag': 0,
        'ect': {
          'start': {
            'day': 9,
            'time': {
              'time': '1200',
              'timeSection': 0
            }
          },
          'end': {
            'day': 9,
            'time': {
              'time': '1200',
              'timeSection': 0
            }
          }
        },
        'targetSOClist': [
          {
            'targetSOClevel': 80,
            'plugType': 0
          },
          {
            'targetSOClevel': 90,
            'plugType': 1
          }
        ]
      }
    },
    'ign3': False,
    'hoodOpen': False,
    'transCond': True,
    'steerWheelHeat': 2,
    'sideBackWindowHeat': 0,
    'tirePressureLamp': {
      'tirePressureLampAll': 0,
      'tirePressureLampFL': 0,
      'tirePressureLampFR': 0,
      'tirePressureLampRL': 0,
      'tirePressureLampRR': 0
    },
    'battery': {
      'batSoc': 75,
      'batState': 0
    },
    'sleepModeCheck': True,
    'time': '20221116143814',
    'remoteWaitingTimeAlert': {
      'remoteControlAvailable': 1,
      'remoteControlWaitingTime': 168,
      'elapsedTime': '00:03:40'
    },
    'systemCutOffAlert': 0,
    'tailLampStatus': 0,
    'hazardStatus': 0
  },
  'odometer': {
    'value': 33724,
    'unit': 1
  }
}

Feature request: tripinfo for specific month and specific day

  • Hyundai / Kia Connect version: 2.1.2 And Bluelink Android App 2.0.7
  • Python version: 3.9.13
  • Operating System: Windows 10

Description

I have been able to sniff the Hyundai Bluelink Android App calls for my IONIQ 5 in Europe, unaware if this information is available in other regions. Especially I was interested in the detailed "My Trip" information, available in the Bluelink App via ... -> MyTrips

See screenshots from the Bluelink Android App:

MyTrips1_2023-01-07-11-26-50

MyTrips2_2023-01-07-11-27-08

The URL to get this tripinfo is:
POST /api/v1/spa/vehicles/[id]/tripinfo HTTP/1.1

So this looks like it is somethink like drvhistory in Europe:
POST /api/v1/spa/vehicles/[id]/drvhistory

There are apparently 2 variants, one to get month info and one to get detailed day info, the difference is in the post message request:

Month info example:

POST data request:

{"tripPeriodType":0,"setTripMonth":"202301"}

POST data response (pretty print):

{
  "retCode": "S",
  "resCode": "0000",
  "resMsg": {
    "tripPeriodType": 0,
    "monthTripDayCnt": 4,
    "tripDayList": [
      {
        "tripDayInMonth": "20230102",
        "tripCntDay": 2
      },
      {
        "tripDayInMonth": "20230103",
        "tripCntDay": 5
      },
      {
        "tripDayInMonth": "20230104",
        "tripCntDay": 2
      },
      {
        "tripDayInMonth": "20230106",
        "tripCntDay": 4
      }
    ],
    "tripDrvTime": 172,
    "tripIdleTime": 17,
    "tripDist": 123,
    "tripAvgSpeed": 46.5,
    "tripMaxSpeed": 108
  },
  "msgId": "...."
}

Day info example:

POST data request:

{"tripPeriodType":1,"setTripDay":"20230103"}

Post data response (pretty print):

{
  "retCode": "S",
  "resCode": "0000",
  "resMsg": {
    "tripPeriodType": 1,
    "offset": 1,
    "dayTripList": [
      {
        "tripDay": "20230103",
        "dayTripCnt": 5,
        "tripDrvTime": 93,
        "tripIdleTime": 12,
        "tripDist": 67,
        "tripAvgSpeed": 51.8,
        "tripMaxSpeed": 102,
        "tripList": [
          {
            "tripTime": "192151",
            "tripDrvTime": 8,
            "tripIdleTime": 0,
            "tripDist": 7,
            "tripAvgSpeed": 58,
            "tripMaxSpeed": 98
          },
          {
            "tripTime": "185404",
            "tripDrvTime": 12,
            "tripIdleTime": 1,
            "tripDist": 7,
            "tripAvgSpeed": 39,
            "tripMaxSpeed": 69
          },
          {
            "tripTime": "143439",
            "tripDrvTime": 34,
            "tripIdleTime": 5,
            "tripDist": 20,
            "tripAvgSpeed": 45,
            "tripMaxSpeed": 86
          },
          {
            "tripTime": "123318",
            "tripDrvTime": 25,
            "tripIdleTime": 3,
            "tripDist": 27,
            "tripAvgSpeed": 76,
            "tripMaxSpeed": 102
          },
          {
            "tripTime": "120539",
            "tripDrvTime": 14,
            "tripIdleTime": 3,
            "tripDist": 6,
            "tripAvgSpeed": 41,
            "tripMaxSpeed": 73
          }
        ]
      }
    ]
  },
  "msgId": "...."
}

How to sniff

For the ones who also want to be able to sniff the calls from the App, this is how I did it (do it at your own risk):

  • Installed NoxPlayer emulator in Windows 10 and emulate Android 5
  • Installed Burp Suite Community Edition on Windows 10
  • Then followed this guide without installing Bluelink App yet: Android App Traffic Decryption using Nox Player - Windows Guide
  • Disabled Root (because Bluelink App will not work on rooted device) and proxy in Android emulator, installed Bluelink App and login with my credentials (with proxy I could not login?)
  • Enabled proxy and opened Bluelink App and in the Burp Suite the decoded https requests/responses were available

Odometer 0

  • Hyundai / Kia Connect version:
  • Python version:
  • Operating System:

Description

On the dashboard the odometer is showing 0
it looks like a timeout is setting it to 0 after a set period of time.

image

What I Did

Noticed it over the last few days and I have updated all versions when available

login failed (HYUNDAY EUROPE)

  • Hyundai / Kia Connect version: latest
  • Python version: 3.9
  • Operating System: Domoticz official Container

Description

I am using the domoticz-hyundai-kia python plugin for Domoticz (https://github.com/CreasolTech/domoticz-hyundai-kia)

What I Did

I am frequently updating both library and Domoticz plugin. Since end of may 2023, then after this error message, I have downgrade charset normalizer to V 2.1 :

2023-07-17 11:07:24.689 Error: Ioniq5: Traceback (most recent call last):
2023-07-17 11:07:24.689 Error: Ioniq5: File "/opt/domoticz/userdata/plugins/domoticz-hyundai-kia/plugin.py", line 68, in
2023-07-17 11:07:24.689 Error: Ioniq5: import requests
2023-07-17 11:07:24.689 Error: Ioniq5: File "/usr/local/lib/python3.9/dist-packages/requests/init.py", line 48, in
2023-07-17 11:07:24.689 Error: Ioniq5: from charset_normalizer import version as charset_normalizer_version
2023-07-17 11:07:24.690 Error: Ioniq5: File "/usr/local/lib/python3.9/dist-packages/charset_normalizer/init.py", line 24, in
2023-07-17 11:07:24.690 Error: Ioniq5: from .api import from_bytes, from_fp, from_path, is_binary
2023-07-17 11:07:24.690 Error: Ioniq5: File "/usr/local/lib/python3.9/dist-packages/charset_normalizer/api.py", line 5, in
2023-07-17 11:07:24.690 Error: Ioniq5: from .cd import (
2023-07-17 11:07:24.690 Error: Ioniq5: File "/usr/local/lib/python3.9/dist-packages/charset_normalizer/cd.py", line 9, in
2023-07-17 11:07:24.690 Error: Ioniq5: from .md import is_suspiciously_successive_range
2023-07-17 11:07:24.690 Error: Ioniq5: AttributeError: PyCapsule_Import "charset_normalizer.md__mypyc.init_charset_normalizer___md" is not valid

After that, I am not able to login anymore

Ioniq5: *** check_and_refresh_token()...
2023-07-17 11:45:24.332 Ioniq5: AuthError: Login Failed

Inverted is_locked status on EU Kia

  • Hyundai / Kia Connect version: 1.34.2
  • Python version: 3.9
  • Operating System: Mac OSX

Description

Retrieving door lock status for an EU Kia E-Niro, the status is the opposite of what it should be.

For instance the Kia app (and raw data response at vehicleStatus.doorLock) show doorLock=True, but vehicle.is_locked shows False.

This appears to be due to line 240 in KiaUvoApiEU.py which has 'not' in front of the variable assignment:

vehicle.is_locked = not get_child_value(state, "vehicleStatus.doorLock")

vs line 279 in the USA file which appears to be correct:

vehicle.is_locked = get_child_value(state, "vehicleStatus.doorLock")

Android Bluelink App language is reset to English when using hyundai_kia_connect_api

  • Hyundai / Kia Connect version: v1.40.11
  • Python version: 3.9.13
  • Operating System: Windows 10 and Raspberry Pi 11 (bullseye)
  • Android Bluelink App: 2.0.7

Description

When the Android Bluelink App language is configured for non-English, by using the hyundai_kia_connect_api the Android Bluelink App is reset to English. So somehow the authentication/login/api does reset the Android Bluelink App to English.

What I Did

I've looked at the source code of hyundai_kia_connect_api and I thought it's the side effect of the following python statement in KiaUvoApiEU.py, line 68:

        if BRANDS[brand] == BRAND_KIA:
            auth_client_id = "f4d531c7-1043-444d-b09a-ad24bd913dd4"
            self.LOGIN_FORM_URL: str = (
                "https://"
                + self.LOGIN_FORM_HOST
                + "/auth/realms/eukiaidm/protocol/openid-connect/auth?client_id="
                + auth_client_id
                + "&scope=openid%20profile%20email%20phone&response_type=code&hkid_session_reset=true&redirect_uri="
                + self.USER_API_URL
                + "integration/redirect/login&ui_locales=en&state=$service_id:$user_id"
            )
        elif BRANDS[brand] == BRAND_HYUNDAI:
            auth_client_id = "64621b96-0f0d-11ec-82a8-0242ac130003"
            self.LOGIN_FORM_URL: str = (
                "https://"
                + self.LOGIN_FORM_HOST
                + "/auth/realms/euhyundaiidm/protocol/openid-connect/auth?client_id="
                + auth_client_id
                + "&scope=openid%20profile%20email%20phone&response_type=code&hkid_session_reset=true&redirect_uri="
                + self.USER_API_URL
                + "integration/redirect/login&ui_locales=en&state=$service_id:$user_id"
            )

The statement "ui_locales=en" could cause the side effect? Should it be "ui_locales=de" for Germany and "ui_locales=nl" for the Netherlands? But changing that, still the language setting in the Android Bluelink App is reset to English.

date/timestamp sometimes wrong, old date/timestamp, while the longitude/latitude has been changed

  • Hyundai / Kia Connect version: v1.52.13
  • Python version: 3.9.13
  • Operating System: Windows 10

Description

Sometimes the location information (latitude and longitude) is changed, but the date/time is the same as the previous date/time stamp.
It could be that this is NOT a problem of the hyundai_kia_connect_api, but a problem of the server sending the wrong date/time stamp, like it also sends the wrong odometer for my IONIQ 5 in combination with infotainment version 221129.

Example of monitor.csv, using monitor.py

2022-12-31 16:28:19+01:00, 5.118544, ....
2022-12-31 16:28:19+01:00, 5.085289, ....
2023-01-02 16:38:09+01:00, 5.118586, ....

The date/time of the second line in this example is wrong, because the longitude is different, but date/timestamp not.
The date should be 2023-01-02 and the time in this case would be around 16:10. So it looks that an old date/time stamp is retrieved.

Could there be another later date/timestamp, which should overrule the general timestamp?

What I Did

I looked at the hyundai_kia_connect_api source code, but could not find directly something wrong there. Also another user did report the same problem, see this post in Dutch.

Unfortunately it is difficult to find the problem, because a next run it could be correct.

odometer not updating during driving, while location and SOC is updating.

  • Hyundai / Kia Connect version: hyundai_kia_connect_api-1.34.2
  • Python version: Python 3.9.13
  • Operating System: Raspberry Pi Bulls Eye and Windows 10

Description

I made Automatic trip administration tools for Hyundai Bluelink or Kia UVO Connect users, using hyundai_kia_connect_api-1.34.2,
named hyundai_kia_connect_monitor

I noticed that odometer is not updated, while locations and SOC is updated while driving.

  • Is this a problem in hyundai_kia_connect_api-1.34.2?
  • Or is this a problem in the bluelink API functionality, that it will update this only when shutting the car down?

Example output monitor.py

datetime, longitude, latitude, engineOn, 12V%, odometer, SOC%, charging, plugged
2022-09-24 11:00:49+02:00, 5.129967, 51.674819, True, 92, 17390.8, 98, False, 0
2022-09-24 11:30:38+02:00, 5.204728, 51.883719, True, 97, 17390.8, 91, False, 0
2022-09-24 12:00:44+02:00, 5.250064, 52.256122, True, 98, 17390.8, 81, False, 0
2022-09-24 12:30:39+02:00, 5.540714, 52.575733, True, 98, 17390.8, 69, False, 0
2022-09-24 13:00:39+02:00, 5.768325, 52.898894, True, 98, 17390.8, 57, False, 0

The odometer keeps 17390.8, while location and SOC is updated when polling each half hour.

I use region = 1 (REGION_EUROPE) and brand = 2 (BRAND_HYUNDAI) and call:

manager.check_and_refresh_token()
manager.check_and_force_update_vehicles(600)

Indirectly KiaUvoApiEU.py is used then.

What I Did

Tried to use manager.force_refresh_all_vehicles_states(), but same result, odometer seems to be updated after turning the car off?

            manager = VehicleManager(
                region=int(REGION),
                brand=int(BRAND),
                username=USERNAME,
                password=PASSWORD,
                pin=PIN
            )
            manager.check_and_refresh_token()
            manager.force_refresh_all_vehicles_states()

Discussion: Using ENUMs

let's create an ENUM to map simple fields (non property) to respective key.

Current code;

vehicle.car_battery_percentage = get_child_value(state, "vehicleStatus.battery.batSoc")
vehicle.engine_is_running = get_child_value(state, "vehicleStatus.engine")

New Code

class FieldDefinition(Enum):
  car_battery_percentage= "vehicleStatus.battery.batSoc"
  engine_is_running="vehicleStatus.engine"

for key, value in FieldDefinition:
  setattr(vehicle, key, get_child_value(value))

odometer not being updated while car in motion

Hyundai / Kia Connect version: latest
Python version: 3.11
Operating System: Windows & Unix

Description

I don't see odometer value only being updated at end of a trip, hence no updates while the car is in motion.

What I Did

I used 
- force_refresh_all_vehicles_states()
and 
- update_all_vehicles_with_cached_state()
to get latest data while car was in motion

Is this a known limitation?

from hyundai_kia_connect_api import * results in TypeError: 'type' object is not subscriptable

  • Hyundai / Kia Connect version:
  • Python version:
  • Operating System:

Description

getting error in first line of example
Describe what you were trying to get done.
Tell us what happened, what went wrong, and what you expected to happen.
first line in example:
from hyundai_kia_connect_api import *

What I Did

python3 
from hyundai_kia_connect_api import *

Paste the command(s) you ran and the output.
If there was a crash, please include the traceback here.

result:

  File "<stdin>", line 1, in <module>
  File "/home/pi/kia/hyundai_kia_connect_api/hyundai_kia_connect_api/__init__.py", line 3, in <module>
    from .ApiImpl import ApiImpl, ClimateRequestOptions
  File "/home/pi/kia/hyundai_kia_connect_api/hyundai_kia_connect_api/ApiImpl.py", line 27, in <module>
    class ApiImpl:
  File "/home/pi/kia/hyundai_kia_connect_api/hyundai_kia_connect_api/ApiImpl.py", line 38, in ApiImpl
    def get_vehicles(self, token: Token) -> list[Vehicle]:
TypeError: 'type' object is not subscriptable

Question on headers and tokens

  • Hyundai / Kia Connect version: 1.40.10

Quick question for you @cdnninja .

I am doing some refactoring in the KiaUvoApiEU class and I am comparing headers in requests.

All authenticated requests use identical headers, except _get_forced_vehicle_state. It passes the refresh token (token.refresh_token) instead of the access token.

This API uses the Oauth2 standard, and if I understand correctly, the refresh token should only be used to get a new access token once the original access token expires.

So, unless the API does not comply with the Oauth2 spec, we should pass the access token like all other requests, no? (unless of course the access token expired, but that should be handled in a separate request)

Looking at the git history, it used to be the case but was modified in early november (@jwefers).

Not an issue but more of a request

I'm trying to intergrade the call flow into my application but can't get it working with postman. You don't happen to have something like that lying around? ๐Ÿ™‚

Thoughts on _get_location

  • Hyundai / Kia Connect version: 1.40.2
  • Python version: 3.9
  • Operating System: MacOS

Description

_get_cached_vehicle_state calls _get_location.
If I understand correctly,_get_location triggers a connection to the car from the manufacturer's servers, to fetch the car's position.
Does it not defeat the whole point of using cached data? Especially since location data is already present in the cached response.

I see there is a "todo" comment to prevent calls when the cached data is "fresh" but even then, should the car be contacted at all when requesting cached data?

My car is parked in an underground parking. The car does appear to have cell service, I'm not sure about GPS coverage. Either way, the API call from _get_location returns this:
'resCode': '4081', 'resMsg': 'Request timeout. - Request timeout.'

The server takes 2 minutes to return this response, which I'm guessing is the timeout for the car-server API. I'm not sure if the car gets the call from the server but fails to get GPS signal, or if the call goes through at all.

"last_updated_at" is not in ISO time format

  • Hyundai / Kia Connect version: 1.18.15
  • Python version: 3.x
  • Operating System:

Description

Date Format is not ISO. Python ISO Time

What I Did

While forwarding the last_updated_at via mqtt to openHAB, I recognized that it isn't correctly parsed in openHAB.
This seems to be due to a missing "T" between date and time e.g:
2022-01-20 09:12:34+01:00
instead of
2022-01-20T09:12:34+01:00

My current workaround is to do an ingress regex REGEX:s/\s/T/g, which I also could do in my python script.
But wouldn't it also be possible to provide the last_update_at additionally in iso, e.g. as last_updated_at_iso?

Climate service fails

Region and Brand of car
EU Kia

Version of the integration
2.0.40

Describe the bug
When Carling the climate service it fails.

Debug logs if an error occurred

Logger: homeassistant.helpers.script.websocket_api_script
Source: custom_components/kia_uvo/coordinator.py:178
Integration: Kia Uvo / Hyundai Bluelink (documentation, issues)
First occurred: 16:51:27 (2 occurrences)
Last logged: 16:51:53

websocket_api script: Error executing script. Unexpected error for call_service at pos 1: _check_response_for_errors() missing 1 required positional argument: 'response'
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 451, in _async_step
    await getattr(self, handler)()
  File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 684, in _async_call_service_step
    await service_task
  File "/usr/src/homeassistant/homeassistant/core.py", line 1744, in async_call
    task.result()
  File "/usr/src/homeassistant/homeassistant/core.py", line 1781, in _execute_service
    await cast(Callable[[ServiceCall], Awaitable[None]], handler.job.target)(
  File "/config/custom_components/kia_uvo/services.py", line 70, in async_handle_start_climate
    await coordinator.async_start_climate(vehicle_id, climate_request_options)
  File "/config/custom_components/kia_uvo/coordinator.py", line 178, in async_start_climate
    await self.hass.async_add_executor_job(
  File "/usr/local/lib/python3.10/concurrent/futures/thread.py", line 58, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/usr/local/lib/python3.10/site-packages/hyundai_kia_connect_api/VehicleManager.py", line 102, in start_climate
    return self.api.start_climate(self.token, self.get_vehicle(vehicle_id), options)
  File "/usr/local/lib/python3.10/site-packages/hyundai_kia_connect_api/KiaUvoApiEU.py", line 504, in start_climate
    _check_response_for_errors()
TypeError: _check_response_for_errors() missing 1 required positional argument: 'response'

To Reproduce
Call service:

service: kia_uvo.start_climate
data:
  device_id: *******
  duration: 10
  defrost: true
  heating: "1"
  climate: true
  temperature: 21

Recommend Projects

  • React photo React

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

  • Vue.js photo Vue.js

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

  • Typescript photo Typescript

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

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

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

  • web

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

  • server

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

  • Machine learning

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

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

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

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.